简体   繁体   English

Matplotlib axvspan() 函数填充错误的日期

[英]Matplotlib axvspan() function fills wrong date

When I want to use axvspan to fill the dates, It fills wrong area.当我想使用 axvspan 填充日期时,它填充了错误的区域。 I think it reversed axvspans.我认为它逆转了 axvspans。 The reason for the problem may be the dataframe that I imported from World Bank.问题的原因可能是我从世界银行导入的数据框。 How can I fix it?我该如何解决? Thank you.谢谢你。

import matplotlib.pyplot as plt
import matplotlib
from pandas_datareader import wb
import seaborn as sns
import pandas as pd
import datetime
start = datetime.datetime (2000,1,1)
end = datetime.datetime (2021,5,1)
ind = ['FM.LBL.BMNY.ZG',
       'FR.INR.DPST'
       ]
df = wb.download(indicator=ind, country='CHN', start=start, end=end).dropna();df.reset_index(inplace=True)
df.columns = ['Country',
              'Year',
              'Broad money growth (annual %) - China',
              'Deposit interest rate (%)'
              ]
df=df.sort_values(by='Year', ascending=True)
axes= df.plot(x='Year',subplots=True, figsize=(20,12), layout=(1,2), colormap='summer', legend=True)

for ax, col in zip(axes.flatten(), df.columns):
    ax.axvspan('2007-1-12', '2009-6-1', color='teal', alpha=0.5,
               label='2008 Crisis')
    ax.axvspan('2019-12-1', '2020-2-1', color='orange', alpha=0.5,
               label='Pandemic')
    ax.set_title(col)

axes[0,0].set_title('Broad money growth (annual %) - China')
axes[0,0].invert_xaxis()
axes[0,0].legend(loc='upper left')
axes[0,0].set_ylabel('Percent(Annual)')
axes[0,0].invert_xaxis()

axes[0,1].set_title('Deposit interest rate (%)')
axes[0,1].invert_xaxis()
axes[0,1].legend(loc='upper left')
axes[0,1].set_ylabel('Percent(Annual)')
axes[0,1].invert_xaxis()



plt.suptitle("Financial Sector in China",fontweight="bold")
plt.show()

您可以看到它没有填写 2019 年,而是填写了另一个日期。

在此处输入图片说明

Correcting xaxis dtype in pandas.plot to correct vspan locations更正 pandas.plot 中的 xaxis dtype 以更正 vspan 位置

The year column in df is an object not an int, so the xlim is (-1, 21) and the labels are formatted on top of those index locations. df 中的 year 列是一个对象而不是 int,所以 xlim 是 (-1, 21) 并且标签被格式化在这些索引位置的顶部。 Therefore, when you go to place your vspan, the x location entered does not match those of the x axis.因此,当您放置 vspan 时,输入的 x 位置与 x 轴的位置不匹配。 To fix this, simply make your year column an int and make your vspan in terms of years as ints.要解决此问题,只需将年份列设为整数,并将以年份为单位的 vspan 设为整数。

在此处输入图片说明

import matplotlib.pyplot as plt
import matplotlib
from pandas_datareader import wb
import seaborn as sns
import pandas as pd
import datetime
import matplotlib.ticker as ticker

start = datetime.datetime (2000,1,1)
end = datetime.datetime (2021,5,1)
ind = ['FM.LBL.BMNY.ZG',
       'FR.INR.DPST'
       ]
df = wb.download(indicator=ind, country='CHN', start=start, end=end).dropna();df.reset_index(inplace=True)
df.columns = ['Country',
              'Year',
              'Broad money growth (annual %) - China',
              'Deposit interest rate (%)'
              ]
df=df.sort_values(by='Year', ascending=True)
df['Year'] = df['Year'].astype(int)

axes= df.plot(x='Year',subplots=True, figsize=(15,5), layout=(1,2), colormap='summer', legend=True)

for ax, col in zip(axes.flatten(), df.columns):
    ax.axvspan(2007, 2009, color='teal', alpha=0.5, label='2008 Crisis')
    ax.axvspan(2019, 2020, color='orange', alpha=0.5, label='Pandemic')
    ax.set_title(col)
    ax.set_xlim(2000, 2021)
    ax.xaxis.set_major_locator(ticker.MultipleLocator(2))

axes[0,0].set_title('Broad money growth (annual %) - China')
axes[0,0].legend(loc='upper left')
axes[0,0].set_ylabel('Percent(Annual)')


axes[0,1].set_title('Deposit interest rate (%)')
axes[0,1].legend(loc='upper left')
axes[0,1].set_ylabel('Percent(Annual)')

plt.suptitle("Financial Sector in China",fontweight="bold")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM