I tried to plot a figure to show all possible markers and got this undesired figure with plt.savefig
,
This is caused by the small figure size (the default figure size: 800x600
pixels).
I can manually increase the figure size with fig.set_size_inches(w, h)
, but I don't know the exact size it should be. Is there a way to autofit the figure size?
I learnt from Resize a figure automatically in matplotlib that passing the option bbox_inches='tight'
to plt.savefig
can automatically resize a figure, but it doesn't work for me. I also tried plt.tight_layout()
, it doesn't work either.
Here is the source code.
from __future__ import division
import matplotlib.pyplot as plt
import matplotlib
import math
import operator
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i+n]
def plot_all_marks(out_file):
"""plot all possible markers"""
fig, axarr = plt.subplots(2, 2)
fig.suptitle('All possible markers in Matplotlib') # Add a centered title to the figure
markers = matplotlib.lines.Line2D.markers # all possiable markers, 35
group_size = int(math.ceil(len(markers)/4))
list_marker_s = sorted(markers.items(), key=operator.itemgetter(1)) # sorted by description
for idx_chunk, l in enumerate(chunks(list_marker_s, group_size)):
# for each group
i, j = divmod(idx_chunk, 2)
for idx, (marker, s) in enumerate(l):
y = [-idx]*5
axarr[i, j].plot(y, 'o', marker=marker,
markeredgecolor='k', # mec
markerfacecolor='b', # mfc
markerfacecoloralt='r', # mfcalt, set the alternate marker face color
markeredgewidth=1.0, # mew, float value in points
fillstyle='none', # fillstyles = ('full', 'left', 'right', 'bottom', 'top', 'none')
markevery=None, # [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
markersize=8, label=s)
axarr[i, j].set_axis_off()
axarr[i, j].legend(loc='center left')
axarr[i, j].set_xlim(-4, 5)
axarr[i, j].set_ylim(-group_size, 1)
axarr[i, j].legend(loc='center left')
plt.tight_layout()
plt.savefig(out_file, bbox_inches='tight')
def main():
# plot all markers
out_file = 'all_marks.png'
plot_all_marks(out_file)
if __name__ == '__main__':
main()
Aucun commentaire:
Enregistrer un commentaire