【问题标题】:Specifying x axis in matplotlib based on dates根据日期在 matplotlib 中指定 x 轴
【发布时间】:2019-06-25 01:16:34
【问题描述】:

我使用的是美联储提供的月度数据。但是,我只想绘制 10 年的数据,所以我将 .tail() 的 10 x 12 个月 = 120 用于月度数据,将 10 x 4 季度用于季度。我的困境是当我绘制数据框时,它在 x 轴上绘制每个月,而我只想每个图每年有 1 个刻度。

# Load in data from .csv files only using the 10 most recent years of data, 120 for monthly 40 for quarterly
federal_funds_df = pd.read_csv("data/FEDFUNDS.csv").tail(120)
CPI_df = pd.read_csv("data/CPIAUCSL.csv").tail(120)
unemployment_df = pd.read_csv("data/UNRATE.csv").tail(120)
real_GDP_df = pd.read_csv("data/GDPC1.csv").tail(40)

# Initialize the plot figure
plt.figure(figsize=(4, 1))
plt.suptitle("U.S. Economic Indicators")

# Effective Federal Funds Rate Plot
plt.subplot(141)
plt.plot(federal_funds_df.DATE, federal_funds_df.FEDFUNDS, label="Federal Funds Rate")
plt.legend(loc='best')

# Consumer Price Index Plot
plt.subplot(142)
plt.plot(CPI_df.DATE, CPI_df.CPIAUCSL, label="Consumer Price Index")
plt.legend(loc='best')

# Civilian Unemployment Rate Plot
plt.subplot(143)
plt.plot(unemployment_df.DATE, unemployment_df.UNRATE, label="Unemployment Rate")
plt.legend(loc='best')

# Real Gross Domestic Product Plot
plt.subplot(144)
plt.plot(real_GDP_df.DATE, real_GDP_df.GDPC1, label="Real GDP")
plt.legend(loc='best')

# Show plots fullscreen
mng = plt.get_current_fig_manager()
mng.window.state('zoomed')
plt.show()

.csv 数据示例:

DATE,FEDFUNDS
1954-07-01,0.80
1954-08-01,1.22
1954-09-01,1.06
1954-10-01,0.85
1954-11-01,0.83
1954-12-01,1.28

【问题讨论】:

  • 不要绘制字符串。先转换为日期。
  • 查看 matplotlib 文档。它提供了一个example 用于设置随时间变化的图的刻度和子刻度。

标签: python pandas matplotlib


【解决方案1】:

您应该将日期转换为date time 格式。如果您发布输入数据的样本会更容易。但类似于以下内容:

pd.to_datetime(df['Date'], format= '%d/%m/%y')

然后您可以对您想要每年绘制的任何项目进行groupby。如需更具体的答案,请发布一些数据。

另请参阅此帖子:Groupby month and year

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 2018-08-31
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2015-05-02
    • 2020-06-09
    相关资源
    最近更新 更多