【问题标题】:Matplotlib x-axis disappearMatplotlib x 轴消失
【发布时间】:2018-10-15 13:15:10
【问题描述】:

我正在尝试使用 python 的 matplotlib 函数,并得到一些奇怪的结果,即 x 轴标签从图中消失了。

我正在尝试Youtube 中所示的以下示例:

在示例中,x 轴显示绘图的年份。 当我尝试在自己的 Jupyter 笔记本中进行操作时,我得到的是以下内容:

代码:

yearly_average[-20:].plot(x='year', y='rating', figsize=(15,10), grid=True)

我该如何解决这个问题?

【问题讨论】:

  • 你的情节设置(你的代码)是什么?没有代码我们很难查明错误
  • 截图显示:yearly_average[-20:].plot(x='year', y='rating', figsize=(15,10), grid=True)

标签: python pandas matplotlib jupyter-notebook


【解决方案1】:

让我们将 yearly_average 数据帧中的 Year 列从 str 或 object dtype 转换为整数。然后,使用 pandas plot 进行绘图。

MVCE:

使用 xaxis 刻度标签的工作示例,其中 dtype 'Year' 为整数

df = pd.DataFrame({'Year':[2000,2001,2002,2003,2004,2005],'Value':np.random.randint(1000,5000,6)})

df.plot('Year','Value')

现在,让我们将 'Year' 转换为 str 并再次测试绘图。

df1 = df.copy()
df1['Year'] = df['Year'].astype(str)
df1.plot('Year','Value')

缺少刻度标签

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    相关资源
    最近更新 更多