以下代码仅将主要类别 ['one', 'two', 'three', 'four', 'five', 'six'] 显示为 x 轴标签。有没有办法将子类别 ['A', 'B', 'C', 'D'] 显示为辅助 x 轴标签?
df = pd.DataFrame(np.random.rand(6, 4),
index=['one', 'two', 'three', 'four', 'five', 'six'],
columns=pd.Index(['A', 'B', 'C', 'D'],
name='Genus')).round(2)
df.plot(kind='bar',figsize=(10,4))
最佳答案
这里有一个解决方案。您可以获取条形的位置并相应地设置一些次要的 xticklabels。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(6, 4),
index=['one', 'two', 'three', 'four', 'five', 'six'],
columns=pd.Index(['A', 'B', 'C', 'D'],
name='Genus')).round(2)
df.plot(kind='bar',figsize=(10,4))
ax = plt.gca()
pos = []
for bar in ax.patches:
pos.append(bar.get_x()+bar.get_width()/2.)
ax.set_xticks(pos,minor=True)
lab = []
for i in range(len(pos)):
l = df.columns.values[i//len(df.index.values)]
lab.append(l)
ax.set_xticklabels(lab,minor=True)
ax.tick_params(axis='x', which='major', pad=15, size=0)
plt.setp(ax.get_xticklabels(), rotation=0)
plt.show()
关于python - 带有多个标签的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43545879/