本文介绍了将索引显示为大 pandas 图的xticks的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框,并试图对其进行绘制,以使其在x轴上显示8-19的索引数据.

I have the following dataframe and am trying to plot it, so that it shows in the x-axis the index data from 8-19.

如果我执行df.plot(),则完全不会显示任何标签.如果我执行df.plot(use_index=True),则行为保持不变.最后,我尝试了df.plot(xticks=df.index),但出现了错误AttributeError: 'NoneType' object has no attribute 'seq'

If I do df.plot() no labels are shown at all. If I do df.plot(use_index=True), the behaviour is unchanged. Finally I tried df.plot(xticks=df.index) but I'm getting an error 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()

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

What is even more strange is that when I do this:

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

xticks将显示,但它们是错误的.只有9-14之间的数字在下雪,而其他所有数字都在下雪.我希望08-19是xticks.

The xticks will show but they are wrong. Only numbers from 9-14 are snown and every other number only. I would expect 08-19 as xticks.

任何建议都值得赞赏.

推荐答案

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

If you want to have string as xticks one possible solution is:

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

这篇关于将索引显示为大 pandas 图的xticks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 01:20