Matplotilb Graphic Chart: Diagonal Tick Labels

I am matplotlib.pyplot histogram in Python using matplotlib.pyplot . The chart will contain a large number of bars, and each bar has its own label. Thus, labels overlap and they are no longer readable. I would like for the labels to be displayed diagonally so that they do not overlap, for example, in this image.

This is my code:

 import matplotlib.pyplot as plt N =100 menMeans = range(N) ind = range(N) ticks = ind fig = plt.figure() ax = fig.add_subplot(111) rects1 = ax.bar(ind, menMeans, align = 'center') ax.set_xticks(ind) ax.set_xticklabels( range(N) ) plt.show() 

How can labels be displayed diagonally?

+9
source share
2 answers

In the example, the documents use:

 plt.setp(xtickNames, rotation=45, fontsize=8) 

so in your case, I would think: ax.set_ticklabels(range(N), rotation=45, fontsize=8) will give you an angle, but they still overlap. So try:

 import matplotlib.pyplot as plt N =100 menMeans = range(N) ind = range(N) ticks = ind fig = plt.figure() ax = fig.add_subplot(111) rects1 = ax.bar(ind, menMeans, align = 'center') ax.set_xticks(range(0,N,10)) ax.set_xticklabels( range(0,N,10), rotation=45 ) plt.show() 

enter image description here

+10
source

Instead of using set_xticks or set_xticklabels , which are not officially recommended , you can simply use the rotation parameter for xticks :

 plt.xticks(rotation=45, ha="right") 

This way you can specify the rotation of the labels, letting matplotlib take care of their frequency / spacing. Please note that using ha="right" to align the label text to the right does not matter if all of your labels are short (and you can delete it in this case), but it is important if your labels are long and of variable length - it guarantees that the end of the tick mark is directly below the tick mark, and prevents inconsistent placement or even overlap of the marks.

Full working example based on code in question:

 import matplotlib.pyplot as plt N =100 menMeans = range(N) ind = range(N) ticks = ind fig = plt.figure() ax = fig.add_subplot(111) rects1 = ax.bar(ind, menMeans, align = 'center') plt.xticks(rotation=45, ha="right") plt.show() 

Exit:

Graph with rotated labels

+11
source

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


All Articles