I am plotting a bar graph by reading data from a CSV using pandas in Python. I read a CSV into a DataFrame
and plot them using matplotlib.
Here is how my CSV looks like:
SegmentName Sample1 Sample2 Sample3
Loop1 100 100 100
Loop2 100 100 100
res = DataFrame(pd.read_csv("results.csv", index_col="SegmentName"))
I plot and set the legend to be outside.
plt.figure()
ax = res.plot(kind='bar')
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.savefig("results.jpg")
However, the x-axis ticklabels are orientated vertically and hence I can't read the text. Also my legend outside is cut off.
Can I change the orientation of the ticklabels to be horizontal, and then adjust the entire figure so that the legend is visible?
To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.
Rotate X-Axis Tick Labels in Matplotlib There are two ways to go about it - change it on the Figure-level using plt. xticks() or change it on an Axes-level by using tick. set_rotation() individually, or even by using ax.
Try using the 'rotation' keyword when you set the label. E.g.:
plt.xlabel('hi',rotation=90)
Or if you need to rotate the tick labels, try:
plt.xticks(rotation=90)
As for the positioning of the legend etc., it is probably worth taking a look at the tight layout guide
For the rotation of the labels, you can simply tell pandas to rotate it for you by giving the number of degrees to the rot
argument.
The legends being cut off is answered elsewhere as well, like here:
df = pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
orient='index', columns=['one', 'two', 'three'])
ax = df.plot(kind='bar', rot=90)
lgd = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
fig.savefig("results.jpg", bbox_extra_artists=(lgd,), bbox_inches='tight')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With