使用matplotlib打印时否决数据框索引

2024-04-16 11:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用数据框进行绘图,但有时,我想对我的x-tick标签进行更多的控制,看起来数据框索引正在“推翻”我的代码。代码如下:

test_df = pd.DataFrame({'cycles':[0,'b',3,'d','e','f','g'],'me':[100,80,99,100,75,100,90], 'you':[100,80,99,100,75,100,90], 'us':[100,80,99,100,75,100,90]})
f, ax = plt.subplots()
x = test_df['me']
x.index = ['a','b','c','d','e','f','g']



print(x)
for a in ax.get_xticklabels():
    a.set_text('me')

print(ax.get_xticklabels()[0])
ax.plot(x)
test_df.plot(x = 'cycles', y = 'me')

有没有更简单的方法可以轻松地修改数据框的x-tick标签,而无需更改数据框的索引,但可以轻松地即时为任何数据框列生成我想要的x-tick


Tags: 数据代码test绘图dfgetplot标签
1条回答
网友
1楼 · 发布于 2024-04-16 11:25:12

您可以在DataFrame.plot中指定xticks。这基本上只是一个假人,以确保勾号标签的数量是正确的

然后,只需在绘图后手动设置记号标签

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'cycles':[0,'b',3,'d','e','f','g'],
                   'me':[100,80,99,100,75,100,90]})

fig, ax = plt.subplots()
test_df.plot(x='cycles', y='me', ax=ax, xticks=test_df.index)
_ = ax.set_xticklabels(test_df['cycles'])
plt.show()

enter image description here

但是,对于XTick是如何不自动生成的,您应该有点犹豫。当值是有序的时,线图是有意义的。对我来说,0应该与'b'连接起来似乎并不明显,而'e'应该与'f'连接起来。在这种情况下,条形图是有意义的,毫不奇怪,生成的XTICK没有问题

test_df.plot(x='cycles', y='me', kind='bar', legend=False)

enter image description here

相关问题 更多 >