【问题标题】:Adding more months to x-axis on the graph在图表的 x 轴上添加更多月份
【发布时间】:2020-05-12 18:18:20
【问题描述】:

这是我的代码,我已经实现了简单的图表,但我想更详细地说明它。

temp_df = pd.read_excel('xTraders_Temperature_Wind.xlsx', sheet_name = 'Temperature')
temp_df = temp_df.drop(columns=['Timestamp end']).set_index('Timestamp start').dropna(subset = \
    ['Average forecast GEFS Turkey National (ºC)', 'Observation Turkey National (ºC)'])


year_data = temp_df.index 
actual_data = temp_df['Observation Turkey National (ºC)']
predicted_data = temp_df['Average forecast GEFS Turkey National (ºC)']

plt.plot(year_data, actual_data, color='red', linewidth = 1)
plt.plot(year_data, predicted_data, color='yellow', linewidth = 0.1)

plt.xlabel('Time')
plt.ylabel('Potential Temperature')
plt.title('Foreast and Observation Temperature')
plt.show()

这些是我的 x 轴:

[2017-01, 2017-05, 2017-09, 2018-01, 2018-05, 2018-09, 2019-01, 2019-05, 2019-09, 2020-01]

(我想要的 x 轴)我想像这样添加更多月份:

[2017-01, 2017-02, 2017-03, 2017-04, 2017-05, 2017-06, 2017-07, 2017-08, 2017-09, 2017-10, 2017-11, 2017-12, \
2018-01, 2018-02, 2018-03, 2018-04, 2018-05, 2018-06, 2018-07, 2018-08, 2018-09, 2018-10, 2018-11, 2018-12, \
2019-01, 2019-02, 2019-03, 2019-04, 2019-05, 2019-06, 2019-07, 2019-08, 2019-09, 2019-10, 2019-11, 2019-12]

我怎样才能做到这一点?

【问题讨论】:

    标签: pandas matplotlib xticks


    【解决方案1】:

    尝试使用Series.reindex

    idx = pd.date_range('01-2017', '12-2019')
    
    temp_df.index = pd.DatetimeIndex(temp_df.index)
    
    temp_df = temp_df.reindex(idx, fill_value=0)
    

    【讨论】:

    • nan 值怎么样,因为我删除了一些 nan 值。如果我用你的方式,我会不会犯错?
    猜你喜欢
    • 2018-02-26
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    相关资源
    最近更新 更多