【问题标题】:Showing index as xticks for pandas plot将索引显示为熊猫图的 xticks
【发布时间】:2019-12-15 22:06:29
【问题描述】:

我有以下数据框并正在尝试绘制它,以便它在 x 轴上显示 8-19 的索引数据。

如果我这样做df.plot(),则根本不会显示任何标签。如果我做df.plot(use_index=True),行为不会改变。最后我尝试了df.plot(xticks=df.index),但我收到了一个错误AttributeError: 'NoneType' object has no attribute 'seq'

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
null = np.nan

df = pd.DataFrame.from_dict({"today sensor 1": {"08": 22.9, "09": 22.7, "10": 22.8, "11": 23.6, "12": 24.1, "13": 24.9,
                                           "14": 25.0, "15": 25.2, "16": 25.7, "17": 26.1, "18": 26.0, "19": 25.8},
                        "today sensor 2": {"08": 24.5, "09": 24.5, "10": 24.8, "11": 25.3, "12": 26.4, "13": 26.7,
                                           "14": 27.1, "15": 27.6, "16": 28.0, "17": 28.0, "18": 28.2, "19": 28.0},
                        "yesterday sensor 1": {"08": null, "09": null, "10": null, "11": null, "12": null, "13": null,
                                               "14": null, "15": null, "16": 23.0, "17": 23.6, "18": 23.5, "19": 23.5},
                        "yesterday sensor 2": {"08": null, "09": null, "10": null, "11": null, "12": null, "13": null,
                                               "14": null, "15": null, "16": 24.8, "17": 24.9, "18": 24.9, "19": 24.8}})

# df.plot(use_index=True)  # does not work
df.plot(xticks=df.index)

plt.show()

更奇怪的是,当我这样做时:

ax = df.plot(use_index=True, style=['bs-', 'go-', 'b:', 'g:'])
ax.set_xticklabels(df.index)
plt.show()

xticks 会显示,但它们是错误的。只有从 9 到 14 的数字是下雪的,并且只有其他数字。我希望 08-19 是 xticks。

欢迎提出任何建议。

【问题讨论】:

  • 是否有必要将字符串作为索引?
  • 索引是小时。该图表是温度图表。我不关心数据类型
  • 如果您不在乎使用整数(或日期时间),那么您的绘图中就会出现 xticks。

标签: python pandas matplotlib


【解决方案1】:

如果您想将字符串作为 xticks,一种可能的解决方案是:

df = df.reset_index()
df = df.rename(columns={"index":"hour"})
ax = df.plot(xticks=df.index)
ax.set_xticklabels(df["hour"]);

【讨论】:

  • 它有效,但显然是熊猫的意外和奇怪的行为
  • 我同意你的看法。我希望有人能弄清楚并向我们解释。
【解决方案2】:

在 Pandas 中的 bug 得到修复之前,在 df.plot() 之后添加这个,不需要其他任何东西:

plt.xticks(range(len(df.index)), df.index)

【讨论】:

  • 如果我只设置该索引的一个子集,比如每 10 次观察,该怎么办?
【解决方案3】:

Python 3.6 (Windows) 的 Pandas 版本 0.24 为我解决了这个问题。

【讨论】:

  • 对我来说是半固定的,但 +1。它仍然只显示每秒钟的刻度和标签。
猜你喜欢
  • 2021-12-18
  • 2021-02-26
  • 2021-11-11
  • 2022-12-04
  • 2018-09-06
  • 2020-11-01
  • 2020-10-03
  • 2016-10-16
  • 2019-01-19
相关资源
最近更新 更多