Matplotlib: Convert the legend to a bitmap [duplicate] - python

This question already has answers here:
Get legend as a separate picture in Matplotlib
(11 answers)
Closed 4 years ago.
I want the legend as a separate bitmap, is that possible with matplotlib?
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot([1,2,3,4,5], [1,2,3,4,5], 'r')
legend = axes.legend()
How would I save legend to bitmap? Any ideas?

If you want to have a legend in a different figure, you can use axes.get_legend_handles_labels() to get the legend handles and labels and add them to a different figure.
Also you need to provide a legend in the first plot, using the label argument, or to explicitly provide a list of labels to associate with the handles.
The following code should do what I suggested in my comment to the question:
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot([1,2,3,4,5], [1,2,3,4,5], 'r', label='test')
legend = axes.legend()
fig2 = plt.figure()
ax = fig2.add_subplot(111)
# add the legend from a different axes
ax.legend(*axes.get_legend_handles_labels())
# hide the spines and the x/y labels
ax.axis('off')
If you want more control for hiding stuff you can hide the axis spines only with
ax.set_frame_on(False)
or the x/y labels with
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

Related

Problem plotting spectrogram colorbar in matplotlib [duplicate]

This question already has answers here:
How to plot in multiple subplots
(12 answers)
Closed 1 year ago.
I want to make a subplot using the input data
I think this is just a question of passing the spectrogram's "mappable" to plt.colorbar() so that it knows what to make a colourbar for. The tricky thing is that it's a bit buried in an attribute of the spectrogram Axes:
fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True)
ax1.plot(time, data1[0].data)
ax2.plot(time, data2.data)
spec = data2.spectrogram(axes=ax3, # <-- Assign a name.
show=True,
samp_rate=20,
per_lap=0.5,
wlen=30,
log=True,
cmap='plasma', # <-- Don't use jet :)
clip=(0.05, 0.2),
)
plt.xlabel('Time')
plt.ylabel('Frequency')
# More flexibility with the positioning:
cbar_ax = fig.add_axes([0.2, 0.0, 0.6, 0.05]) # Left, bottom, width, height.
cbar = fig.colorbar(spec.collections[0], # <-- Get the mappable.
cax=cbar_ax,
orientation='horizontal')
cbar.set_label('Colorbar label')
plt.show()
This also shows how to position the colorbar where you want. And I changed your colourmap to plasma because you shouldn't use jet.

Increasing the h-size of plots in plt.subplot() inside a loop - Python [duplicate]

This question already has answers here:
How do I change the size of figures drawn with Matplotlib?
(14 answers)
Closed 4 years ago.
I have this code:
for i in ["Dia", "DiaSemana", "Mes", "Año", "Feriado"]:
plt.subplot(1,2,1)
sns.boxplot(x=i, y="Y", data=df)
plt.subplot(1,2,2)
sns.boxplot(x=i, y="Temp", data=df)
plt.tight_layout()
plt.show()
It gives me all the plots I need. Here is one-time loop:
As you can see, the x axis is overlapped and I'm trying to increase the horizontal size of each plot in order to have a better visualization.
You are limited by the width of your figure. You can make your figure wider with the figsize attribute. You can "grab" your figure by either explicitly defining it (plt.figure) or getting the current figure (plt.gcf).
However, I prefer is using plt.subplots to define both figure and axes:
for i in ["Dia", "DiaSemana", "Mes", "Año", "Feriado"]:
fig, axes = plt.subplots(ncols=2, figsize=(15, 5)) # set width of figure and define both figure and axes
sns.boxplot(x=i, y="Y", data=df, ax=axes[0])
sns.boxplot(x=i, y="Temp", data=df, ax=axes[1])
plt.tight_layout()
plt.show()
Alternatively, you could decrease the number of ticks in the x axis.

How to hide axes and gridlines in Matplotlib (python) [duplicate]

This question already has answers here:
How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)
(11 answers)
Closed 5 years ago.
I would like to be able to hide the axes and gridlines on a 3D matplotlib graph. I want to do this because when zooming in and out the image gets pretty nasty. I'm not sure what code to include here but this is what I use to create the graph.
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.view_init(30, -90)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plt.xlim(0,pL)
plt.ylim(0,pW)
ax.set_aspect("equal")
plt.show()
This is an example of the plot that I am looking at:
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
Note, you need matplotlib>=1.2 for set_zticks() to work.
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)

How to shrink plot on x-axis in matplotlib?

I've seen a couple examples but the plots are constructed differently and I don't see how to make the syntax work. Here's my code:
pdf_file = PdfPages(sys.argv[1].split('.')[0] + "_graphs.pdf")
for i in range(0, len(list_of_data)):
biorep = int(list_of_figure_key[i].split('.')[1])
construct = int(list_of_figure_key[i].split('.')[0].split('_')[1])
plot(time, list_of_data[i], color=color_dict[construct], linestyle=linestyle_dict[biorep], label=list_of_figure_key[i] )
xlabel('time (hours)', fontsize=9)
ylabel(ReadType, fontsize=9)
xlim(min(time),max(time))
legend(fontsize=8, loc='center left', bbox_to_anchor=(1, .5))
pdf_file.savefig()
It produces a beautiful figure but the legend is much too long and goes off the edge of the page. I'd like to shrink the plot on the x-axis so the legend will fit as a 2-column legend.
Figure can be seen here: http://i.imgur.com/mvgzIhj.jpg
Thanks in advance!
You can make a two-column legend using the ncol legend attribute. You can shrink the width of the plot by drawing the axis on the plot and fixing its size:
from matplotlib import pyplot as plt
fig = plt.figure() # initialize figure
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # add axis
To make this work with your code, something like this should work:
# import pyplot
from matplotlib import pyplot as plt
# set up filename to save it
pdf_file = PdfPages(sys.argv[1].split('.')[0] + "_graphs.pdf")
# set up axis object
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# plot your data
for i in range(0, len(list_of_data)):
biorep = int(list_of_figure_key[i].split('.')[1])
construct = int(list_of_figure_key[i].split('.')[0].split('_')[1])
ax.plot(time, list_of_data[i], color=color_dict[construct],
linestyle=linestyle_dict[biorep], label=list_of_figure_key[i] )
# modify axis limits and legend
ax.set_xlabel('time (hours)', fontsize=9)
ax.set_ylabel(ReadType, fontsize=9)
ax.set_xlim(min(time),max(time))
ax.legend(fontsize=8, loc='upper left', bbox_to_anchor=(1, .5), ncol=2)
# save final figure
plt.savefig(pdf_file)
In your code, you were remaking the legend, the limits and the legend at each iteration of the for-loop, as well as saving and then overwriting the pdf image. This isn't necessary -- you can just do it once at the end.
For more legend tips, this post is handy. This one is also helpful.

matplotlib fig size with colorbar

I'm trying to produce two figure. The second one is equal to the first one, with the only exception that it has superimposed an image with the corresponding colorbar. I need this in a presentation for a correct overlay. The code I'm using is the following
import matplotlib as mpl
# first figure
fig = mpl.pylab.figure(figsize=(10, 7))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.plot(x,y)
ax.set_xlabel(r'x')
ax.set_ylabel(r'y')
ax.set_xlim([0,1])
ax.set_ylim([0,1])
mpl.pylab.savefig('one.pdf',bbox_inches='tight')
# second figure
fig = mpl.pylab.figure(figsize=(10, 7))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.plot(x,y)
ax.set_xlabel(r'x')
ax.set_ylabel(r'y')
ax.set_xlim([0,1])
ax.set_ylim([0,1])
im = ax.imshow(image,aspect='auto',origin='lower',extent=(0,1,0.5,1))
cb = fig.colorbar(im, orientation='vertical')
cb.set_label(r'p$_e$ [Pa]', fontsize = 18)
mpl.pylab.savefig('two.pdf',bbox_inches='tight')
The problem is that I would like that the canvas (I think this is the correct name, i.e. the space occupied by the axis and label) to be exactly the same for the two figures, whereas the second one is shrink because of the colorbar. How can I correctly determine the size for the figures?
Check out this post
You can also check out this example
I would recommend either plotting both plots on the same figure, making a grid, or doing a separate colorbar as in this example
import matplotlib as mpl
# first plot
plt.subplot(131)
...
# second plot
plt.subplot(132)
...
#colorbar
plt.subplot(133)
...

Categories

Resources