Python 打印精简的自定义文本-matplotlib
我有一个熊猫数据帧“g”,有两列,看起来像: 我尝试使用以下代码绘制它:Python 打印精简的自定义文本-matplotlib,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有一个熊猫数据帧“g”,有两列,看起来像: 我尝试使用以下代码绘制它: g.plot(x = 'date', y = 'some_value', kind = 'bar', figsize = (10, 5), legend = False) plt.xlabel("date") plt.ylabel("some value") plt.show() 这将生成以下图表: 这是因为从2018年1月2日开始到2018年12月11日结束共有318天的数据
g.plot(x = 'date', y = 'some_value', kind = 'bar', figsize = (10, 5), legend = False)
plt.xlabel("date")
plt.ylabel("some value")
plt.show()
这将生成以下图表:
这是因为从2018年1月2日开始到2018年12月11日结束共有318天的数据,所有这些数据都被绘制出来,导致x轴混乱且无法读取
我想减少x轴上的标签数量,以包含间隔,例如每15天。我怎样才能做到
我找到了一个,但它谈到用自定义文本替换相同数量的间隔,这不是我的问题。我想用自定义文本减少间隔的数量
谢谢 通过将日期列转换为pd.datetime索引,使数据帧成为时间序列
dt= pd.to_datetime(g['dates'],format="%Y-%m-%d")
g.index=dt
然后matplotlib将自动调整x比例和标签
g.plot( y = ['some_value'])
manu190466
的答案应该是时间序列的默认方式。如果出于任何原因需要自定义标签,您可以始终使用setxticklabels
来决定显示/隐藏哪些标签以及它们应该是什么:
import pandas as pd
# Tweak as per desired logic. Entirely up to you what to show
# To hide a label simply return None for it
def my_labels(data):
# Show only odd-positioned labels
return ['Custom: '+d[0] if i%2==0 else None for i,d in enumerate(data)]
data = [['2021-01-01',1],['2021-01-02',2],['2021-01-03',3]]
df = pd.DataFrame(data,columns=['date','value'])
ax = df.value.plot(xticks=df.index, rot=90)
ax.set_xticklabels(my_labels(data))
ax
我尝试了你的代码,但它不起作用。请给出一个可复制的示例,以便我可以在上面测试我的代码。