【问题标题】:How to set xticks label for specific data instead of every data?如何为特定数据而不是每个数据设置 xticks 标签?
【发布时间】:2020-04-23 12:46:37
【问题描述】:

我有一个这种格式的数据。

使用上面的数据,我使用下面的代码创建了一个图表。

from matplotlib import pyplot

pyplot.figure(figsize=(12,8))
pyplot.plot(df_movie['date'], df_movie['rate'], label = 'rating')
pyplot.xticks(rotation=90)
pyplot.legend(loc='best')
pyplot.grid()
pyplot.show()

下面是这段代码的结果。

每个日期都有 xticks 标签。但我希望每周或每隔 10 天左右显示 xticks 标签。我该怎么做?

谢谢

【问题讨论】:

  • this答案中尝试解决方案

标签: python pandas dataframe matplotlib label


【解决方案1】:

这是一个非常简单的方法。您可以将参数interval 设置为 7 或 10 或您喜欢的任何其他值:

import matplotlib.pyplot as plt
import matplotlib.ticker as tkr

x = list('ABCDEFGHIJ')
y = [1,2,4,8,16,32,64,128,256,512]

fig, ax = plt.subplots(1)

interval = 2 # This parameter regulates the interval between xticks

plt.plot(x,y)
ax.xaxis.set_major_locator(tkr.MultipleLocator(interval))
plt.show()

【讨论】:

    【解决方案2】:

    您应该首先将日期列设置为正确的类型。

    df_amovie['date'] = pd.to_datetime(df_amovie['date'])
    

    然后,如果你绘制你可能会得到想要的结果。

    【讨论】:

    • 谢谢你的回答,但我想指定xtick标签的间隔而不是默认值。
    猜你喜欢
    • 2019-03-14
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 2016-04-15
    相关资源
    最近更新 更多