Periodic grayscale colormap - matplotlib

To plot an angle, I need an intuitive periodic colormap. I found the 'hsv' colormap (https://matplotlib.org/users/colormaps.html) which is periodic, but very not intuitive because to me green is not further away from blue than from yellow for example.
I think a periodic grayscale colormap is exactly what I need: changing smoothly from black in both edges to white in the middle (or the other way around).
I could not find this colormap in the built-in ones. Does anyone know of such existing colormap or a way to manually define it?

The easiest way to create a the desired black-white-black colormap is to use matplotlib.colors.LinearSegmentedColormap.from_list()
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
colors = ["black", "white", "black"]
cmap=LinearSegmentedColormap.from_list("", colors)
Then use it as any usual colormap:
import numpy as np
r = np.linspace(0,1)
t = np.linspace(0,2*np.pi, 360)
R,T = np.meshgrid(r,t)
fig, ax = plt.subplots(subplot_kw=dict(projection="polar"))
ax.pcolormesh(T,R,T, cmap=cmap)
plt.show()

Related

how to change color of axis in 3d matplotlib figure?

The color of the axis (x, y, z) in a 3d plot using matplotlib is black by default. How do you change the color of the axis? Or better yet, how do you make them invisible?
%matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.xaxis.set_visible(False) # doesn't do anything
And there doesn't seem to be a ax.xaxis.set_color function. Any thoughts on how to make the axis invisible or change the color?
You can combine your method with the approach provided here. I am showing an example that affects all three axes. In Jupyter Notebook, using tab completion after ax.w_xaxis.line., you can discover other possible options
ax.w_xaxis.line.set_visible(False)
ax.w_yaxis.line.set_color("red")
ax.w_zaxis.line.set_color("blue")
To change the tick colors, you can use
ax.xaxis._axinfo['tick']['color']='r'
ax.yaxis._axinfo['tick']['color']='g'
ax.zaxis._axinfo['tick']['color']='b'
To hide the ticks
for line in ax.xaxis.get_ticklines():
line.set_visible(False)

changing the size of subplots with matplotlib

I am trying to plot multiple rgb images with matplotlib
the code I am using is:
import numpy as np
import matplotlib.pyplot as plt
for i in range(0, images):
test = np.random.rand(1080, 720,3)
plt.subplot(images,2,i+1)
plt.imshow(test, interpolation='none')
the subplots appear tiny though as thumbnails
How can I make them bigger?
I have seen solutions using
fig, ax = plt.subplots()
syntax before but not with plt.subplot ?
plt.subplots initiates a subplot grid, while plt.subplot adds a subplot. So the difference is whether you want to initiate you plot right away or fill it over time. Since it seems, that you know how many images to plot beforehand, I would also recommend going with subplots.
Also notice, that the way you use plt.subplot you generate empy subplots in between the ones you are actually using, which is another reason they are so small.
import numpy as np
import matplotlib.pyplot as plt
images = 4
fig, axes = plt.subplots(images, 1, # Puts subplots in the axes variable
figsize=(4, 10), # Use figsize to set the size of the whole plot
dpi=200, # Further refine size with dpi setting
tight_layout=True) # Makes enough room between plots for labels
for i, ax in enumerate(axes):
y = np.random.randn(512, 512)
ax.imshow(y)
ax.set_title(str(i), fontweight='bold')

Different level of transparency for edgeline and fill in matplotlib or seaborn distribution plot

I would like to set different levels of transparency (= alpha) for the edge line and fill of a distribution plot that I created in matplotlib/seaborn. For example:
ax1 = sns.distplot(BSRDI_DF, label="BsrDI", bins=newBins, kde=False,
hist_kws={"edgecolor": (1,0,0,1), "color":(1,0,0,0.25)})
The above approach does not work, unfortunately. Does anybody have any idea how I could accomplish this?
The problem seems to be that seaborn sets an alpha parameter for the histogram. While alpha defaults to None for a usual histogram, such that something like
plt.hist(x, lw=3, edgecolor=(1,0,0,0.75), color=(1,0,0,0.25))
works as expected, seaborn sets this alpha to some given value. This overwrites the alpha that is set in the RGBA tuples.
The solution is to set alpha explicitely to None:
ax = sns.distplot(x, kde=False, hist_kws={"lw":3, "edgecolor": (1,0,0,0.75),
"color":(1,0,0,0.25),"alpha":None})
A complete example:
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(60)
ax = sns.distplot(x, label="BsrDI", bins=np.linspace(-3,3,10), kde=False,
hist_kws={"lw":3, "edgecolor": (1,0,0,0.75),
"color":(1,0,0,0.25),"alpha":None})
plt.show()
EDIT Nevermind, I thought using color instead of facecolor was causing the problem but it seems the output that I got only looked right because the patches were overlapping, giving seemingly darker edges.
After investigating the issue further, it looks like seaborn is hard-setting the alpha level at 0.4, which supersedes the arguments passed to hist_kws=
sns.distplot(x, kde=False, hist_kws={"edgecolor": (1,0,0,1), "lw":5, "facecolor":(0,1,0,0.1), "rwidth":0.8})
While using the same parameters to plt.hist() gives:
plt.hist(x, edgecolor=(1,0,0,1), lw=5, facecolor=(0,1,0,0.1), rwidth=0.8)
Conclusion: if you want different alpha levels for edges and face colors, you'll have to use matplotlib directly, and not seaborn.

Seaborn stripplot set edgecolor based on hue/palette

I'm trying to create a figure like this one from the seaborn documentation but with the edgecolor of the stripplot determined by the hue. This is my attempt:
import seaborn as sns
df = sns.load_dataset("tips")
ax = sns.stripplot(x="sex", y="tip", hue="day", data=df, jitter=True,
edgecolor=sns.color_palette("hls", 4),
facecolors="none", split=False, alpha=0.7)
But the color palettes for male and female appear to be different. How do I use the same color palette for both categories?
I'm using seaborn 0.6.dev
The edgecolor parameter is just passed straight through to plt.scatter. Currently you're giving it a list of 4 colors. I'm not exactly sure what I would expect it to do in that case (and I am not exactly sure why you end up with what you're seeing here), but I would not have expected it to "work".
The ideal way to have this work would be to have a "hollow circle" marker glyph that colors the edges based on the color (or facecolor) attribute rather than the edges. While it would be nice to have this as an option in core matplotlib, there are some inconsistencies that might make that unworkable. However, it's possible to hack together a custom glyph that will do the trick:
import numpy as np
import matplotlib as mpl
import seaborn as sns
sns.set_style("whitegrid")
df = sns.load_dataset("tips")
pnts = np.linspace(0, np.pi * 2, 24)
circ = np.c_[np.sin(pts) / 2, -np.cos(pts) / 2]
vert = np.r_[circ, circ[::-1] * .7]
open_circle = mpl.path.Path(vert)
sns.stripplot(x="sex", y="tip", hue="day", data=df,
jitter=True, split=False,
palette="hls", marker=open_circle, linewidth=0)
FWIW I should also mention that it's important to be careful when using this approach because the colors become much harder to distinguish. The hls palette exacerbates the problem as the lime green and cyan middle colors end up quite similar. I can imagine situations where this would work nicely, though, for instance a hue variable with two levels represented by gray and a bright color, where you want to emphasize the latter.

how can i color specific pixels in matplotlib imshow?

I am plotting a numpy matrix with imshow and nearest neighbor interpolation in blue scale.
How can i color specific pixels in the plot so that they would be, say red?
pyplot.imshow(matrix, interpolation='nearest',cmap = cm.Blues)
pyplot.show()
You can't directly color pixels red with a colormap that doesn't have red in it. You could pick a red-blue colormap and norm your matrix data into the blue part, but you can also just plot over an imshow image:
from matplotlib import pyplot
from numpy.random import random
matrix = random((12,12))
from matplotlib import cm
pyplot.imshow(matrix, interpolation='nearest', cmap=cm.Blues)
pyplot.scatter([6,8], [10,7], color='red', s=40)
pyplot.show()