I am trying to add colorbar for each subplot. The 3D data is like (x,y,z). My codes are like:
fig,ax = plt.subplots(2,2,figsize=(15,15))
ax[0,0].scatter(x,y,s=z,c=z,cmap='jet')
ax[0,0].set_xlabel('XXX')
ax[0,0].set_ylabel('YYY')
So I am able to add x,y labels, add title for each subplot, but I just can't add the colorbar.
My codes for colorbar in a single plot are like:
plt.colorbar(extend='both')
or
colorbar = plt.colorbar(label='test',orientation='horizontal',shrink=0.8,pad=0.05,extend='both')
I saw the previous Q&A here matplotlib colorbar in each subplot, but sorry I don't understand how to apply to my case. Is there a way to add the colorbar, just like how I added the xlabel and title, please? Many thanks.
Related
I am using plotly to show an image using fig=px.imshow(img)
I would like it to have a discret legend similar to the ones in the pie chart or the bar chart: fig2 = px.pie(df, values=df[0],names=df.index,color =df.index, color_discrete_map= h.colormap)
imshow() does not have the argument color_discret_map but maybe there could be a work-around ?
I know it is possible with matplotlib but I need plotly to do it.
I know how to make a lattice plot (https://seaborn.pydata.org/tutorial/axis_grids.html) or relationship plot (https://seaborn.pydata.org/generated/seaborn.relplot.html#seaborn.relplot).
However, what if each inidivdual plot needs to be a plot with 2 Y-axis? And within each plot, there are 4 lines, 3 lines using the left Y-axis and 1 line using the right Y-axis, something like the figure below:
So instead of the 4 scatter plots such as the figure below from the seaborn documentation, I need 4 of my double Y-axis figures... ... I am think of using the FacetGrid function, but it seems like my argument must be an sns plot that can be written in one line only, and I cannot use the matplotlib twinx() function.
Any help is greatly appreciated, thank you!
I have followed the post here in order to smooth a 3D scatter plot I have.
My original scatter plot is,
And I would like to get a smooth plot like the following one, that was made using Mathematica,
In the post I mentioned, they use the trisurf function to get a smoother plot. So I though I could use the same to get a similar plot. However, what I get is
As you can see, the triangulation did not work properly. And I don't know how to fix it.
Does anybody know a way to fix this problem? Or is there any other function I could use to smooth my scatter plot?
I think I should mention that my scatter plot is NOT a surface, it is a volume.
Thank you.
Just to clarify this, I post my codes for the original and the trisurf plot eventhough there isn't much to see.
Scatter plot:
S=pd.read_csv("SeparableStatesGrafica.csv",header=None,names=
['P0','P1','P2','P3','P4'])
G=plt.figure().gca(projection='3d')
G.scatter(S['P1'], S['P3'], S['P0'],color='red')
G.set_xlabel("P1")
G.set_ylabel("P3")
G.set_zlabel("P0")
G.view_init(40,40)
plt.show()
Trisurf plot:
S=pd.read_csv("SeparableStatesGrafica.csv",header=None,names=
['P0','P1','P2','P3','P4'])
p0=S['P0'].values
p1=S['P1'].values
p3=S['P3'].values
fig = pylab.figure(figsize=pyplot.figaspect(.96))
ax = Axes3D(fig)
ax.plot_trisurf(p1, p3, p0)
ax.set_xlabel("p1")
ax.set_ylabel("p3")
ax.set_zlabel("p0")
ax.view_init(40,40)
plt.show()
I've got scatter plot with colorbar which I save as PNG image. I need the plot to be of a certain figsize but adding colorbar scales original plot.
import pylab as plt
plt.figure(figsize=FIGSIZE)
plt.scatter(X, Y, c=Z, s=marker_size, norm=LogNorm(), vmin=VMIN, vmax=VMAX, cmap=CMAP,rasterized=True,lw=0,)
CB = plt.colorbar(ticks=TICKS, format=FORMAT)
How could I save original plot (with figsize set as above) and colorbar as two separate images?
The obvious answer is "plot your colorbar separately". You need to create a new figure window and plot your colorbar there, in order to prevent your first figure from being distorted. Small example:
import matplotlib.pyplot as plt
import numpy as np # only for dummy data
X,Y = np.mgrid[-2:3,-2:3]
Z = np.random.rand(*X.shape)
FIGSIZE = (2,3)
plt.figure(figsize=FIGSIZE)
mpb = plt.pcolormesh(X,Y,Z,cmap='viridis')
# plot the original without a colorbar
plt.savefig('plot_nocbar.png')
# plot a colorbar into the original to see distortion
plt.colorbar()
plt.savefig('plot_withcbar.png')
# draw a new figure and replot the colorbar there
fig,ax = plt.subplots(figsize=FIGSIZE)
plt.colorbar(mpb,ax=ax)
ax.remove()
plt.savefig('plot_onlycbar.png')
# save the same figure with some approximate autocropping
plt.savefig('plot_onlycbar_tight.png',bbox_inches='tight')
Consider the following four figures that were produced (click to view properly):
The first is a saved version of the figure without a call to colormap. This is fine, this is what you want to preserve. The second figure shows what happens if we call colorbar without any extra fuss: it takes some space from the original figure, and this is what you want to prevent.
You have to open a new figure (and axes) using plt.subplots, with the size of your original figure. This way you can be sure that the produced colorbar will be the same size as if it was drawn in your original figure. In the above setup I let matplotlib determine the size of the colorbar itself; but then afterward we need to delete the auxiliary axes that would pollute the resulting plot. (The other option would be to create a single axes in the new figure manually, with the expected size of the colorbar. I suspect this is not a feasible course of action.)
Now, as you can see in the third plot, the empty space left after the deleted axes is clearly visible in the resulting plot (but the size of the colorbar is perfect, correspondingly). You can either cut this white space off manually in post-production, or use something that autocrops your colorbar image.
I also included a version of the plot wherein matplotlib itself crops most of the figure: the bbox_inches='tight' keyword argument to savefig does exactly this. The upside is that the resulting image file only contains the colorbar (as seen above in the fourth image), but the size of the resulting colorbar will be slightly different from your original. Depending on your specific needs, you'll need to experiment with the available methods to come up with a solution that's most convenient for you.
Is there a way to enlarge the axis-scale label in matplotlib (circled in red in the enlarged plot below)?
I've used ax.tick_params() to successfully edit the tick labels, but I haven't been able to find anything about this specific piece of the plot.
Worse comes to worst, I could go with a manual text() insertion, but I'd like something more direct if possible.
Add a line like this
ax.xaxis.get_children()[1].set_size(15)
To change your major tick scale label (I guess we can call it so) to 15 points, if you plot the plot on ax.
If you plot using the pyplot API, add a line of ax=plt.gca() as well.