Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the ticklabel orientation and legend position of plot

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?

enter image description here

like image 640
user2450971 Avatar asked Aug 07 '13 08:08

user2450971


People also ask

How do I change the legend position in my plot?

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.

How do I change the orientation of Xlabel Matplotlib?

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.


Video Answer


2 Answers

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

like image 110
Dman2 Avatar answered Oct 22 '22 17:10

Dman2


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')
like image 23
Mahdi Avatar answered Oct 22 '22 16:10

Mahdi