I am plotting changes in mean and variance of some data with the following code
import matplotlib.pyplot as pyplot
import numpy
vis_mv(data, ax = None):
if ax is None: ax = pyplot.gca()
cmap = pyplot.get_cmap()
colors = cmap(numpy.linspace(0, 1, len(data)))
xs = numpy.arange(len(data)) + 1
means = numpy.array([ numpy.mean(x) for x in data ])
varis = numpy.array([ numpy.var(x) for x in data ])
vlim = max(1, numpy.amax(varis))
# variance
ax.imshow([[0.,1.],[0.,1.]],
cmap = cmap, interpolation = 'bicubic',
extent = (1, len(data), -vlim, vlim), aspect = 'auto'
)
ax.fill_between(xs, -vlim, -varis, color = 'white')
ax.fill_between(xs, varis, vlim, color = 'white')
# mean
ax.plot(xs, means, color = 'white', zorder = 1)
ax.scatter(xs, means, color = colors, edgecolor = 'white', zorder = 2)
return ax
This works perfectly fine:
but now I would like to be able to use this visualisation also in a vertical fashion as some kind of advanced color bar kind of thingy next to another plot. I hoped it would be possible to rotate the entire axis with all of its contents,
but I could only find this question, which does not really have a solid answer yet either. Therefore, I tried to do it myself as follows:
from matplotlib.transforms import Affine2D
ax = vis_mv()
r = Affine2D().rotate_deg(90) + ax.transData
for x in ax.images + ax.lines + ax.collections:
x.set_transform(r)
old = ax.axis()
ax.axis(old[2:4] + old[0:2])
This almost does the trick (note how the scattered points, which used to lie along the white line, are blown up and not rotated as expected).
Unfortunately the PathCollection holding the result of the scattering does not act as expected. After trying out some things, I found that scatter has some kind of offset transform, which seems to be the equivalent of the regular transform in other collections.
x = numpy.arange(5)
ax = pyplot.gca()
p0, = ax.plot(x)
p1 = ax.scatter(x,x)
ax.transData == p0.get_transform() # True
ax.transData == p1.get_offset_transform() # True
It seems like I might want to change the offset transform instead for the scatter plot, but I did not manage to find any method that allows me to change that transform on a PathCollection. Also, it would make it a lot more inconvenient to do what I actually want to do.
Would anyone know if there exists a possibility to change the offset transform?
Thanks in advance
Unfortunately the PathCollection does not have a .set_offset_transform() method, but one can access the private _transOffset attribute and set the rotating transformation to it.
import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D
from matplotlib.collections import PathCollection
import numpy as np; np.random.seed(3)
def vis_mv(data, ax = None):
if ax is None: ax = plt.gca()
cmap = plt.get_cmap()
colors = cmap(np.linspace(0, 1, len(data)))
xs = np.arange(len(data)) + 1
means = np.array([ np.mean(x) for x in data ])
varis = np.array([ np.var(x) for x in data ])
vlim = max(1, np.amax(varis))
# variance
ax.imshow([[0.,1.],[0.,1.]],
cmap = cmap, interpolation = 'bicubic',
extent = (1, len(data), -vlim, vlim), aspect = 'auto' )
ax.fill_between(xs, -vlim, -varis, color = 'white')
ax.fill_between(xs, varis, vlim, color = 'white')
# mean
ax.plot(xs, means, color = 'white', zorder = 1)
ax.scatter(xs, means, color = colors, edgecolor = 'white', zorder = 2)
return ax
data = np.random.normal(size=(9, 9))
ax = vis_mv(data)
r = Affine2D().rotate_deg(90)
for x in ax.images + ax.lines + ax.collections:
trans = x.get_transform()
x.set_transform(r+trans)
if isinstance(x, PathCollection):
transoff = x.get_offset_transform()
x._transOffset = r+transoff
old = ax.axis()
ax.axis(old[2:4] + old[0:2])
plt.show()
Related
I want to generate a plot like the below:
At the moment I am trying to play around with the alpha parameter:
import numpy as np
from matplotlib import pyplot as plt
xlocations_edensity = np.loadtxt("edensity_xaxis.txt")
ylocations_edensity = np.loadtxt("edensity_yaxis.txt")
xlocsedensity, ylocsedensity = np.meshgrid(xlocations_edensity, ylocations_edensity)
xlocations_Efield = np.loadtxt("Efield_x_axis.txt")
ylocations_Efield = np.loadtxt("Efield_y_axis.txt")
xlocsEfield, ylocsEfield = np.meshgrid(xlocations_Efield, ylocations_Efield)
edensitytensor = np.load("edensitytensor.npy") # shape (76, 257, 65)
Efieldtensor = np.load("Efieldtensor.npy")
fig, ax = plt.subplots()
ax.set(xlabel="x position [um]", ylabel="y position [um] \n")
pos2 = ax.pcolor(xlocations_Efield, ylocations_Efield, Efieldtensor[40, :, :].T, cmap="Reds", alpha=0.9)
fig.colorbar(pos2, ax=ax, label="\n Efield value [MV/m]")
pos1 = ax.pcolor(xlocations_edensity, ylocations_edensity, edensitytensor[100, :, :].T, cmap="Blues", alpha=0.5)
fig.colorbar(pos1, ax=ax, label="\n electron density value [cm^(-3)]")
plt.savefig("Efield_edensity_map.pdf")
But changing the order of plotting, I get different results. One color map ''hides'' the other.
Say I plot the Reds one first, it appears and the Blues one is hidden.
The other way around, Blues first and Reds first, the Blues hides the Reds.
The result of the above code is:
Do you have anything in mind what shall I do?
Thank you!
Setting the alpha value of the pcolor call is not that good because it applies the same transparency to all the colors on the colormap.
You could use a custom colormap with an evolving transparency, I present my try with linear and sigmoidal evolutions of alpha, you could try others. I created dummy noisy data with a Gaussian pulse to simulate the data as in your example.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
# generating dummy data
nx, ny = 257, 65
x_field, y_field = np.linspace(0,10,nx), np.linspace(0,6,ny)
field = np.random.rand(nx,ny)
# normalizing
field -= np.min(field); field /= np.max(field)
x_density, y_density = np.linspace(1,6,nx), np.linspace(1,6,ny)
Y, X = np.meshgrid(y_density,x_density,)
density = np.random.rand(nx,ny) # shape (76, 257, 65)
gaussian_center = (4.0,4.0)
distance_square = (X - gaussian_center[0])**2 + (Y - gaussian_center[1])**2
density += 5.0*np.exp(-distance_square/4.0)
# normalizing
density -= np.min(density); density /= np.max(density)
# getting the original colormap
orig_cmap = plt.get_cmap('Blues')
cmap_n = orig_cmap.N
derived_cmap = orig_cmap(np.arange(cmap_n))
fig, axs = plt.subplots(
4,3,
gridspec_kw={"width_ratios":[1, 0.025, 0.025]},
figsize=(10,8),
constrained_layout=True)
# original
row_subplot = 0
ax = axs[row_subplot,0]
ax.set_ylabel("original")
image_field = ax.pcolor(
x_field, y_field, field.T,
cmap="Reds", shading='auto')
fig.colorbar(image_field, cax=axs[row_subplot,-2],)
image_density = ax.pcolor(
x_density, y_density, density.T,
cmap=orig_cmap, shading="auto")
fig.colorbar(image_density, cax=axs[row_subplot,-1],)
# option 1 - transparent pseudocolor for the above image
row_subplot = 1
ax = axs[row_subplot,0]
ax.set_ylabel("transparent pcolor")
image_field = ax.pcolor(
x_field, y_field, field.T,
alpha=1.0, cmap="Reds", shading='auto')
fig.colorbar(image_field, cax=axs[row_subplot,-2],)
image_density = ax.pcolor(
x_density, y_density, density.T,
alpha=0.5, cmap=orig_cmap, shading="auto")
fig.colorbar(image_density, cax=axs[row_subplot,-1],)
# option 2 - linear gradient colormap
linear_cmap = derived_cmap.copy()
linear_cmap[:,-1] = np.arange(cmap_n)/cmap_n
linear_cmap = ListedColormap(linear_cmap)
row_subplot = 2
ax = axs[row_subplot,0]
ax.set_ylabel("linear gradient")
image_field = ax.pcolor(
x_field, y_field, field.T,
cmap="Reds", shading='auto')
fig.colorbar(image_field, cax=axs[row_subplot,-2],)
image_density = ax.pcolor(
x_density, y_density, density.T,
cmap=linear_cmap, shading="auto")
fig.colorbar(image_density, cax=axs[row_subplot,-1],)
# option 3 - sigmoid gradient
sigmoid_cmap = derived_cmap.copy()
x = np.linspace(-10,10,cmap_n)
sigmoid_cmap[:,-1] = np.exp(x)/(np.exp(x) + 1)
sigmoid_cmap = ListedColormap(sigmoid_cmap)
row_subplot = 3
ax = axs[row_subplot,0]
ax.set_ylabel("sigmoid gradient")
image_field = ax.pcolor(
x_field, y_field, field.T,
cmap="Reds", shading='auto')
fig.colorbar(image_field, cax=axs[row_subplot,-2],)
image_density = ax.pcolor(
x_density, y_density, density.T,
cmap=sigmoid_cmap, shading="auto")
fig.colorbar(image_density, cax=axs[row_subplot,-1],)
I'm updating dynamically a plot in a loop:
dat=[0, max(X[:, 0])]
fig = plt.figure()
ax = fig.add_subplot(111)
Ln, = ax.plot(dat)
Ln2, = ax.plot(dat)
plt.ion()
plt.show()
for i in range(1, 40):
ax.set_xlim(int(len(X[:i])*0.8), len(X[:i])) #show last 20% data of X
Ln.set_ydata(X[:i])
Ln.set_xdata(range(len(X[:i])))
Ln2.set_ydata(Y[:i])
Ln2.set_xdata(range(len(Y[:i])))
plt.pause(0.1)
But now I want to update it in a different way: append some values and show them in other colour:
X.append(other_data)
# change colour just to other_data in X
The result should look something like this:
How could I do that?
Have a look at the link I posted. Linesegments can be used to plot colors at a particular location differently. If you want to do it in real-time you can still use line-segments. I leave that up to you.
# adjust from https://stackoverflow.com/questions/38051922/how-to-get-differents-colors-in-a-single-line-in-a-matplotlib-figure
import numpy as np, matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
# my func
x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
y = 3000 * np.sin(x)
# select how to color
cmap = ListedColormap(['r','b'])
norm = BoundaryNorm([2000,], cmap.N)
# get segments
xy = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.hstack([xy[:-1], xy[1:]])
# control which values have which colors
n = y.shape[0]
c = np.array([plt.cm.RdBu(0) if i < n//2 else plt.cm.RdBu(255) for i in range(n)])
# c = plt.cm.Reds(np.arange(0, n))
# make line collection
lc = LineCollection(segments,
colors = c
# norm = norm,
)
# plot
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.axvline(x[n//2], linestyle = 'dashed')
ax.annotate("Half-point", (x[n//2], y[n//2]), xytext = (4, 1000),
arrowprops = dict(headwidth = 30))
fig.show()
Background
In Matplotlib, we can render the string using mathtext as a marker using $ ..... $ (Reference 1)
Question
Is there any way to enclose this text in a circular or rectangular box, or any different different shape? Similar to the registered symbol as shown here
I want to use this marker on a plot as shown below:
Text '$T$' is used in this plot, I want the text to be enclosed in a circle or rectangle.
Solution
As suggested in the comments of the answer, I have plotted a square marker of a bit larger size before the text marker. This resolved the issue.
The final figure is shown below:
Edit: Easiest way is to simply place patches to be the desired "frames" in the same location as the markers. Just make sure they have a lower zorder so that they don't cover the data points.
More sophisticated ways below:
You can make patches. Here is an example I used to make a custom question mark:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.markers as m
fig, ax = plt.subplots()
lim = -5.8, 5.7
ax.set(xlim = lim, ylim = lim)
marker_obj = m.MarkerStyle('$?$') #Here you place your letter
path = marker_obj.get_path().transformed(marker_obj.get_transform())
path._vertices = np.array(path._vertices)*8 #To make it larger
patch = mpl.patches.PathPatch(path, facecolor="cornflowerblue", lw=2)
ax.add_patch(patch)
def translate_verts(patch, i=0, j=0, z=None):
patch._path._vertices = patch._path._vertices + [i, j]
def rescale_verts(patch, factor = 1):
patch._path._vertices = patch._path._vertices * factor
#translate_verts(patch, i=-0.7, j=-0.1)
circ = mpl.patches.Arc([0,0], 11, 11,
angle=0.0, theta1=0.0, theta2=360.0,
lw=10, facecolor = "cornflowerblue",
edgecolor = "black")
ax.add_patch(circ)#One of the rings around the questionmark
circ = mpl.patches.Arc([0,0], 10.5, 10.5,
angle=0.0, theta1=0.0, theta2=360.0,
lw=10, edgecolor = "cornflowerblue")
ax.add_patch(circ)#Another one of the rings around the question mark
circ = mpl.patches.Arc([0,0], 10, 10,
angle=0.0, theta1=0.0, theta2=360.0,
lw=10, edgecolor = "black")
ax.add_patch(circ)
if __name__ == "__main__":
ax.axis("off")
ax.set_position([0, 0, 1, 1])
fig.canvas.draw()
#plt.savefig("question.png", dpi=40)
plt.show()
Edit, second answer:
creating a custom patch made of other patches:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import mpl_toolkits.mplot3d.art3d as art3d
class PlanetPatch(mpl.patches.Circle):
"""
This class combines many patches to make a custom patch
The best way to reproduce such a thing is to read the
source code for all patches you plan on combining.
Also make use of ratios as often as possible to maintain
proportionality between patches of different sizes"""
cz = 0
def __init__(self, xy, radius,
color = None, linewidth = 20,
edgecolor = "black", ringcolor = "white",
*args, **kwargs):
ratio = radius/6
mpl.patches.Circle.__init__(self, xy, radius,
linewidth = linewidth*ratio,
color = color,
zorder = PlanetPatch.cz,
*args, **kwargs)
self.set_edgecolor(edgecolor)
xy_ringcontour = np.array(xy)+[0, radius*-0.2/6]
self.xy_ringcontour = xy_ringcontour - np.array(xy)
self.ring_contour = mpl.patches.Arc(xy_ringcontour,
15*radius/6, 4*radius/6,
angle =10, theta1 = 165,
theta2 = 14.5,
fill = False,
linewidth = 65*linewidth*ratio/20,
zorder = 1+PlanetPatch.cz)
self.ring_inner = mpl.patches.Arc(xy_ringcontour,
15*radius/6, 4*radius/6,
angle = 10, theta1 = 165 ,
theta2 = 14.5,fill = False,
linewidth = 36*linewidth*ratio/20,
zorder = 2+PlanetPatch.cz)
self.top = mpl.patches.Wedge([0,0], radius, theta1 = 8,
theta2 = 192,
zorder=3+PlanetPatch.cz)
self.xy_init = xy
self.top._path._vertices=self.top._path._vertices+xy
self.ring_contour._edgecolor = self._edgecolor
self.ring_inner.set_edgecolor(ringcolor)
self.top._facecolor = self._facecolor
def add_to_ax(self, ax):
ax.add_patch(self)
ax.add_patch(self.ring_contour)
ax.add_patch(self.ring_inner)
ax.add_patch(self.top)
def translate(self, dx, dy):
self._center = self.center + [dx,dy]
self.ring_inner._center = self.ring_inner._center +[dx, dy]
self.ring_contour._center = self.ring_contour._center + [dx,dy]
self.top._path._vertices = self.top._path._vertices + [dx,dy]
def set_xy(self, new_xy):
"""As you can see all patches have different ways
to have their positions updated"""
new_xy = np.array(new_xy)
self._center = new_xy
self.ring_inner._center = self.xy_ringcontour + new_xy
self.ring_contour._center = self.xy_ringcontour + new_xy
self.top._path._vertices += new_xy - self.xy_init
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot()
lim = -8.5, 8.6
ax.set(xlim = lim, ylim = lim,
facecolor = "black")
planets = []
colors = mpl.colors.cnames
colors = [c for c in colors]
for x in range(100):
xy = np.random.randint(-7, 7, 2)
r = np.random.randint(1, 15)/30
color = np.random.choice(colors)
planet = PlanetPatch(xy, r, linewidth = 20,
color = color,
ringcolor = np.random.choice(colors),
edgecolor = np.random.choice(colors))
planet.add_to_ax(ax)
planets.append(planet)
fig.canvas.draw()
#plt.savefig("planet.png", dpi=10)
plt.show()
I am plotting changes in mean and variance of some data with the following code
import matplotlib.pyplot as pyplot
import numpy
vis_mv(data, ax = None):
if ax is None: ax = pyplot.gca()
cmap = pyplot.get_cmap()
colors = cmap(numpy.linspace(0, 1, len(data)))
xs = numpy.arange(len(data)) + 1
means = numpy.array([ numpy.mean(x) for x in data ])
varis = numpy.array([ numpy.var(x) for x in data ])
vlim = max(1, numpy.amax(varis))
# variance
ax.imshow([[0.,1.],[0.,1.]],
cmap = cmap, interpolation = 'bicubic',
extent = (1, len(data), -vlim, vlim), aspect = 'auto'
)
ax.fill_between(xs, -vlim, -varis, color = 'white')
ax.fill_between(xs, varis, vlim, color = 'white')
# mean
ax.plot(xs, means, color = 'white', zorder = 1)
ax.scatter(xs, means, color = colors, edgecolor = 'white', zorder = 2)
return ax
This works perfectly fine:
but now I would like to be able to use this visualisation also in a vertical fashion as some kind of advanced color bar kind of thingy next to another plot. I hoped it would be possible to rotate the entire axis with all of its contents,
but I could only find this question, which does not really have a solid answer yet either. Therefore, I tried to do it myself as follows:
from matplotlib.transforms import Affine2D
ax = vis_mv()
r = Affine2D().rotate_deg(90) + ax.transData
for x in ax.images + ax.lines + ax.collections:
x.set_transform(r)
old = ax.axis()
ax.axis(old[2:4] + old[0:2])
This almost does the trick (note how the scattered points, which used to lie along the white line, are blown up and not rotated as expected).
Unfortunately the PathCollection holding the result of the scattering does not act as expected. After trying out some things, I found that scatter has some kind of offset transform, which seems to be the equivalent of the regular transform in other collections.
x = numpy.arange(5)
ax = pyplot.gca()
p0, = ax.plot(x)
p1 = ax.scatter(x,x)
ax.transData == p0.get_transform() # True
ax.transData == p1.get_offset_transform() # True
It seems like I might want to change the offset transform instead for the scatter plot, but I did not manage to find any method that allows me to change that transform on a PathCollection. Also, it would make it a lot more inconvenient to do what I actually want to do.
Would anyone know if there exists a possibility to change the offset transform?
Thanks in advance
Unfortunately the PathCollection does not have a .set_offset_transform() method, but one can access the private _transOffset attribute and set the rotating transformation to it.
import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D
from matplotlib.collections import PathCollection
import numpy as np; np.random.seed(3)
def vis_mv(data, ax = None):
if ax is None: ax = plt.gca()
cmap = plt.get_cmap()
colors = cmap(np.linspace(0, 1, len(data)))
xs = np.arange(len(data)) + 1
means = np.array([ np.mean(x) for x in data ])
varis = np.array([ np.var(x) for x in data ])
vlim = max(1, np.amax(varis))
# variance
ax.imshow([[0.,1.],[0.,1.]],
cmap = cmap, interpolation = 'bicubic',
extent = (1, len(data), -vlim, vlim), aspect = 'auto' )
ax.fill_between(xs, -vlim, -varis, color = 'white')
ax.fill_between(xs, varis, vlim, color = 'white')
# mean
ax.plot(xs, means, color = 'white', zorder = 1)
ax.scatter(xs, means, color = colors, edgecolor = 'white', zorder = 2)
return ax
data = np.random.normal(size=(9, 9))
ax = vis_mv(data)
r = Affine2D().rotate_deg(90)
for x in ax.images + ax.lines + ax.collections:
trans = x.get_transform()
x.set_transform(r+trans)
if isinstance(x, PathCollection):
transoff = x.get_offset_transform()
x._transOffset = r+transoff
old = ax.axis()
ax.axis(old[2:4] + old[0:2])
plt.show()
How to reduce the colorbar limit when used with contourf ? The color bound from the graphs itself are well set with "vmin" and "vmax", but the colorbar bounds are not modified.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(20)
y = np.arange(20)
data = x[:,None]+y[None,:]
X,Y = np.meshgrid(x,y)
vmin = 0
vmax = 15
#My attempt
fig,ax = plt.subplots()
contourf_ = ax.contourf(X,Y,data, 400, vmin=vmin, vmax=vmax)
cbar = fig.colorbar(contourf_)
cbar.set_clim( vmin, vmax )
# With solution from https://stackoverflow.com/questions/53641644/set-colorbar-range-with-contourf
levels = np.linspace(vmin, vmax, 400+1)
fig,ax = plt.subplots()
contourf_ = ax.contourf(X,Y,data, levels=levels, vmin=vmin, vmax=vmax)
cbar = fig.colorbar(contourf_)
plt.show()
solution from "Set Colorbar Range in matplotlib" works for pcolormesh, but not for contourf. The result I want looks like the following, but using contourf.
fig,ax = plt.subplots()
contourf_ = ax.pcolormesh(X,Y,data[1:,1:], vmin=vmin, vmax=vmax)
cbar = fig.colorbar(contourf_)
Solution from "set colorbar range with contourf" would be ok if the limit were extended, but not if they are reduced.
I am using matplotlib 3.0.2
The following always produces a bar with colours that correspond to the colours in the graph, but shows no colours for values outside of the [vmin,vmax] range.
It can be edited (see inline comment) to give you exactly the result you want, but that the colours of the bar then still correspond to the colours in the graph, is only due to the specific colour map that's used (I think):
# Start copied from your attempt
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(20)
y = np.arange(20)
data = x[:, None] + y[None, :]
X, Y = np.meshgrid(x, y)
vmin = 0
vmax = 15
fig, ax = plt.subplots()
# Start of solution
from matplotlib.cm import ScalarMappable
levels = 400
level_boundaries = np.linspace(vmin, vmax, levels + 1)
quadcontourset = ax.contourf(
X, Y, data,
level_boundaries, # change this to `levels` to get the result that you want
vmin=vmin, vmax=vmax
)
fig.colorbar(
ScalarMappable(norm=quadcontourset.norm, cmap=quadcontourset.cmap),
ticks=range(vmin, vmax+5, 5),
boundaries=level_boundaries,
values=(level_boundaries[:-1] + level_boundaries[1:]) / 2,
)
Always correct solution that can't handle values outside [vmin,vmax]:
Requested solution:
I am not sure how long it has been there, but in matplotlib 3.5.0 in contourf there is an "extend" option which makes a cutesy little arrow on the colorbar. See the contourf help page. In your scenario we can do
fig,ax = plt.subplots()
contourf_ = ax.contourf(X,Y,data, levels=np.linspace(vmin,vmax,400),extend='max')
cbar = fig.colorbar(contourf_,ticks=range(vmin, vmax+3, 3))