问题
I'm trying to find a solution to a situation where I have multiple xlabels in the plot, which I cannot give up any.
The problem is that the xlabels are running on each other, making the plot not readable (as in subplot(1,1)
)
I was wondering if I can somehow make each second label in another hight (as in the example attached)
What I had in mind:
回答1:
Two approaches
Add a positive rotation to the ticks/labels: https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.xticks.html
Add two new-lines to every even x-label. The code is taken from https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/bar_stacked.html#sphx-glr-gallery-lines-bars-and-markers-bar-stacked-py and modified with a list comprehension that does this (and also modified so the labels are kind of big, like yours)
import numpy as np
import matplotlib.pyplot as plt
# call this function in xticks parameters
def transform_xlabels(xlabels):
return ('\n\n%s' % label if i % 2 else label for i, label in enumerate(xlabels))
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, menMeans, width, yerr=menStd)
p2 = plt.bar(ind, womenMeans, width,
bottom=menMeans, yerr=womenStd)
plt.ylabel('Scores')
plt.title('Scores by group')
test = 'G1 abc \ndaido misco iso'
xlabels = ('G1 %s' % test, 'G2 %s' % test, 'G3 %s' % test, 'G4 %s' % test, 'G5 %s' % test)
# function is called
plt.xticks(ind, transform_xlabels(xlabels))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
plt.show()
Output
来源:https://stackoverflow.com/questions/60399815/matplotlib-multiple-overlapping-xlabels-in-2-levels