简体   繁体   English

plot 减少自定义文本 - matplotlib

[英]plot reduced custom text - matplotlib

I have a pandas dataframe 'g' having two columns and looks like:我有一个 pandas dataframe 'g' 有两列,看起来像:

在此处输入图像描述

I am trying to plot it using the code:我正在尝试使用代码 plot 它:

g.plot(x = 'date', y = 'some_value', kind = 'bar', figsize = (10, 5), legend = False)
plt.xlabel("date")
plt.ylabel("some value")
plt.show()

which produces the following graph:产生下图: 在此处输入图像描述

This happens since there are 318 days of data starting on 2018-01-02 and ending on 2018-12-11, all of which are plotted resulting in a messy and unreadable x-axis.发生这种情况是因为有 318 天的数据从 2018-01-02 开始到 2018-12-11 结束,所有这些都被绘制成一个混乱且不可读的 x 轴。

I want to reduce the number of labels on x-axis to contain intervals for say every 15 days.我想减少 x 轴上的标签数量以包含每 15 天的间隔。 How can I do so?我该怎么做?

I found an answer but it talks about replacing the same number of intervals with a custom text which is not my problem.我找到了答案,但它谈到用自定义文本替换相同数量的间隔,这不是我的问题。 I want to reduce the number of intervals with a custom text.我想减少自定义文本的间隔数。

Thanks!谢谢!

manu190466 's answer should be the default way to go for time series. manu190466的答案应该是时间序列的默认方式 go。 If for whatever reason you want something custom, you can always use set_xticklabels to decide which labels to show/hide and what they should be:如果出于某种原因你想要定制一些东西,你总是可以使用set_xticklabels来决定显示/隐藏哪些标签以及它们应该是什么:

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

在此处输入图像描述

Make your DataFrame a TimeSerie by converting the date column to an pd.datetime index通过将日期列转换为 pd.datetime 索引,使您的 DataFrame 成为 TimeSerie

dt= pd.to_datetime(g['dates'],format="%Y-%m-%d")
g.index=dt

Then matplotlib will auto adjust the x scale and the labels然后 matplotlib 将自动调整 x 比例和标签

g.plot( y = ['some_value'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM