So I'm trying to do a bar plot on a data where x
is the username (string ) and each x
is long enough to overlap each other, so I have to rotate the x
label. No problem there. However, when exporting the plot results, the x
label on the exported image is cropped. I tried using plt.tight_layout()
and worked, but it change the look of the plot. The code is similar to this
from matplotlib import pyplot as plt
x= ['abc', 'ronaldo', 'melon_killer_123456']
y= [1, 2, 3]
plt.bar(x, y)
plt.xticks(rotation = 90)
plt.savefig('a.png')
plt.show()
Exported image:
I want it to look like this (Got this by using jupyter notebook and manually save output image):
So how to do that?
CodePudding user response:
You can play around with the rcParams size settings and the plt.subplots_adjust
settings until you get your desired image.
import matplotlib.pyplot as plt
x= ['abc', 'ronaldo', 'melon_killer_123456']
y= [1, 2, 3]
plt.rcParams["figure.figsize"] = (5,10)
plt.bar(x, y)
plt.xticks(rotation = 90)
plt.subplots_adjust(top=0.925,
bottom=0.20,
left=0.07,
right=0.90,
hspace=0.01,
wspace=0.01)
plt.savefig('a.png')
plt.show()
CodePudding user response:
So i got another answer by assign a Bbox
instance to bbox_inches
parameter on plt.savefig()
function. With this Bbox
we can define xmin
, ymin
xmax
and ymax
of our saved figure (Bbox([[xmin, ymin],[xmax, ymax]])
). The default value is xmin=0
, ymin=0
xmax=figure_width
and ymax=figure_height
If the problem is on the bottom of the saved figure, we need just configure (lower) the ymin
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
x= ['abc', 'ronaldo', 'melon_killer_123456']
y= [1, 2, 3]
plt.bar(x, y)
plt.xticks(rotation = 90)
plt.savefig('a.png', bbox_inches=Bbox([[0,-2],fig.get_size_inches()]))
plt.show()
P.s fig.get_size_inches()
give us a list of the fig size