【问题标题】:How to remove periods with no data from a datetime axis in Matplotlib?如何从 Matplotlib 中的日期时间轴中删除没有数据的期间?
【发布时间】:2021-06-28 17:21:46
【问题描述】:

所以我有一个带有日期时间索引的数据框。我删除了某些时期的行,但是当我绘制数据时,matplotlib 仍然显示删除的时期(例如:2021-03-21 到 2021-03-24)。

这是对这些时期的调用:

df['2021-03-21':'2021-03-23]

这是情节的代码:

dfStd = df.resample('d').std()
fig, ax = plt.subplots(figsize=(16,3))
bp = sns.barplot(x = dfStd.index.strftime('%d-%b'), y='Feed_tph', data=dfStd , color='darkorange', ax=ax)
ax.set_ylabel('Dry Feed [tph]')
ax.set_xlabel('')
plt.xticks(rotation = 90)

如何从图中删除这些句点?

【问题讨论】:

  • 你能编辑问题和一些重现问题的代码吗?更容易提供帮助。

标签: python pandas dataframe matplotlib seaborn


【解决方案1】:

从数据框中删除不需要的条

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

df = pd.DataFrame({
        "time": pd.concat([pd.Series(pd.date_range(d, freq="D", periods=6))
                           for d in pd.date_range("1-jun-2021", freq="10D", periods=4)]),
        "Feed_tph": np.random.uniform(1,10, 6*4)}).set_index("time")

# insert some NaNs..
df2 = pd.Series(index=pd.date_range(df.index.min(), df.index.max()), dtype="float64", name="filler")
df = df.join(df2, how="right").drop(columns=["filler"])

fig, ax = plt.subplots(2,1, figsize=(16,3))
bp = sns.barplot(x = df.index.strftime('%d-%b'), y='Feed_tph', data=df , color='darkorange', ax=ax[0])
df = df.dropna()

bp = sns.barplot(x = df.index.strftime('%d-%b'), y='Feed_tph', data=df , color='darkorange', ax=ax[1])

for i in range(len(ax)):
    ax[i].set_ylabel('Dry Feed [tph]')
    ax[i].set_xlabel('')
    ax[i].set_xticklabels(ax[i].get_xticklabels(), rotation=90)

【讨论】:

  • 谢谢。实际上我已经尝试将日期时间索引转换为字符串,并且它有效,但是这样做非常无效,因为显示图需要很长时间,并且在我的分析中我必须创建 +20 个图。有没有办法保留日期时间索引?
猜你喜欢
  • 1970-01-01
  • 2020-02-02
  • 2012-12-26
  • 2019-07-05
  • 2015-05-02
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多