Change the label orientation and position of the chart legend

I draw a histogram reading data from CSV using pandas in Python. I read the CSV in a DataFrame and built them using matplotlib.

This is what 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 draw and set the legend 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 marks are oriented vertically and therefore I cannot read the text. Also my legend is off outside.

Can I change the orientation of the checkmark to horizontal, and then adjust the entire drawing so that the legend is visible?

enter image description here

+6
source share
3 answers

Try using the rotation keyword when you set the label. For instance:.

 plt.xlabel('hi',rotation=90) 

Or, if you need to rotate tick marks, try:

 plt.xticks(rotation=90) 

Regarding the positioning of the legend, etc., it is probably worth a look at the dense placement guide

+6
source

You should use the matplotlib API and call ax.set_xticklabels(res.index, rotation=0) as follows:

 index = Index(['loop1', 'loop2'], name='segment_name') data = [[100] * 3, [100] * 3] columns = ['sample1', 'sample2', 'sample3'] df = DataFrame(data, index=index, columns=columns) fig, ax = subplots() df.plot(ax=ax, kind='bar', legend=False) ax.set_xticklabels(df.index, rotation=0) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) fig.savefig('results.png', bbox_inches='tight') 

To get the received schedule:

enter image description here

Alternatively, you can call fig.autofmt_xdate() for a nice tilting effect, which you can, of course, work with the above (and more general) ax.set_xticklabels() :

 fig, ax = subplots() df.plot(ax=ax, kind='bar', legend=False) fig.autofmt_xdate() ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) fig.savefig('results-tilted.png', bbox_inches='tight') 

enter image description here

+4
source

To rotate labels, you can simply say pandas to rotate it for you by specifying the number of degrees in the rot argument. The legends section also responds elsewhere, for example 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') 
+4
source

Source: https://habr.com/ru/post/951202/


All Articles