gpt4 book ai didi

python - 带有多个标签的条形图

转载 作者:IT老高 更新时间:2023-10-28 21:13:06 26 4
gpt4 key购买 nike

以下代码仅将主要类别 ['one', 'two', 'three', 'four', 'five', 'six'] 显示为 x 轴标签。有没有办法将子类别 ['A', 'B', 'C', 'D'] 显示为辅助 x 轴标签? enter image description here

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()

enter image description here

关于python - 带有多个标签的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43545879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com