【问题标题】:How to rotate axis label and hide some of them?如何旋转轴标签并隐藏其中一些?
【发布时间】:2020-09-23 23:52:35
【问题描述】:

我试图绘制一个时间序列及其差异。

但是,我的 x 轴标签有两个问题:

  1. 它没有旋转;
  2. 月数太多,画布空间太小。

如何旋转所有标签并隐藏一些日期?

由于机密性,我无法显示数据。但它基本上是一个包含系列和(日期)索引的(数字)列。

这是我到目前为止所做的:

import numpy as np, pandas as pd
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
import matplotlib.pyplot as plt
plt.rcParams.update({'figure.figsize':(9,7), 'figure.dpi':120})

# Original Series
fig, axes = plt.subplots(3, 2, sharex=True);
axes[0, 0].plot(df.teste); 
axes[0, 0].set_title('Original Series');
axes[0,0].set_xticklabels(df.index,rotation=90)
plot_acf(df.teste, ax=axes[0, 1]);

# 1st Differencing
axes[1, 0].plot(df.teste.diff()); 
axes[1, 0].set_title('1st Order Differencing');
plot_acf(df.teste.diff().dropna(), ax=axes[1, 1]);

# 2nd Differencing
axes[2, 0].plot(df.teste.diff().diff()); 
axes[2, 0].set_title('2nd Order Differencing');
axes[2,0].set_xticklabels(df.index,rotation=90)
plot_acf(df.teste.diff().diff().dropna(), ax=axes[2, 1]);

这是输出:

【问题讨论】:

  • 仅供参考:彻底回答问题非常耗时。如果您的问题已解决,请通过接受最适合您的需求的解决方案表示感谢。 位于答案左上角的 / 箭头下方。如果出现更好的解决方案,则可以接受新的解决方案。如果您的声望超过 15,您也可以使用 / 箭头对答案的有用性进行投票。 如果解决方案不能回答问题,请发表评论What should I do when someone answers my question?。谢谢

标签: python pandas matplotlib time-series


【解决方案1】:

检查此代码:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 1000)
y = np.sin(x)

fig, ax = plt.subplots(1, 2, figsize = (8, 4))

ax[0].plot(x, y, 'r-', lw = 2)
ax[0].set_xticks(np.arange(0, 10, 0.25))

ax[1].plot(x, y, 'r-', lw = 2)
ax[1].set_xticks(np.arange(0, 10, 1))
locs, labels = plt.xticks()
plt.setp(labels, rotation = 90)

plt.show()

这给了我这个情节作为例子:

如您所见,两个图表具有相同的选项,但在第二个(右侧)中,我设置了:

ax[1].set_xticks(np.arange(0, 10, 1))

xticks 隔开以删除其中的一些,并且

locs, labels = plt.xticks()
plt.setp(labels, rotation = 90)

旋转它们的方向。

【讨论】:

  • 我仍然不知道如何在我的情况下应用它。当我使用 axes[2, 0].set_xticks(np.arange(0, len(df2), 3)) 时,我得到了我想要的,但只是为了右下角的图表。另一个还有一个乱七八糟的标签
  • 因为在写 axes[2, 0] 时,您正在指定该图。循环遍历所有图 [i, j] 并以相同的方法应用它们
  • 奇怪...我尝试了所有组合,但没有一个有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 2021-11-05
  • 2012-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多