微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Matplotlib 在两条线之间着色

如何解决使用 Matplotlib 在两条线之间着色

我想使用 axvspan() 函数来可视化我使用 Pandas DataReader 获得的 DataFrame。但是当我使用以下代码时,我看到一个错误并且子图中没有阴影。我应该怎么办? 谢谢。

import matplotlib.pyplot as plt
import pandas_datareader.data as pdr
import pandas as pd
import datetime
start = datetime.datetime (2000,1,1)
end = datetime.datetime (2021,5,1)
df  = pdr.DataReader(['WFRBSB50215','WFRBST01134','WFRBST01122','WFRBSN09139','WFRBSB50189','WFRBST01110','WFRBSB50191'],'fred',start,end)
df.columns = ['Share of Total Net Worth Held by the Bottom 50% (1st to 50th Wealth percentiles)','Share of Total Net Worth Held by the Top 1% (99th to 100th Wealth percentiles)','Share of Corporate Equities and Mutual Fund Shares Helb By Top1%(99th to 100th Wealth percentiles)','Share of Financial Assets Held by the 90th to 99th Wealth percentiles','Share of Total Assets Held by the Bottom 50% (1st to 50th Wealth percentiles)','Share of Real Estate Held by the Top 1% (99th to 100th Wealth percentiles)','Share of Real Estate Held by the Bottom %50(1st to 50th Wealth percentiles)'
              ]
ax = df.plot(subplots=True,layout=(7,1),figsize=(15,15),linewidth=3.5,colormap="summer")
ax.axvspan('2007-1-12','2009-6-1',color='c',alpha=0.5)
ax.axvspan('2019-12-1','2020-2-1',color= 'orange',alpha=0.5)
plt.xlabel('Date')
ax[0,].set_title('Share of Total Net Worth Held by the Bottom 50%')
ax[0,].set_ylabel('Percent of Aggregate')
ax[1,].set_title('Share of Total Net Worth Held by the Top 1%')
ax[1,].set_ylabel('Percent of Aggregate')
ax[2,].set_title('Share of Corporate Equities and Mutual Fund Shares Helb By Top 1%')
ax[2,].set_ylabel('Percent of Aggregate')
ax[3,].set_title('Share of Financial Assets Held by the 90th to 99th Wealth percentiles')
ax[3,].set_ylabel('Percent of Aggregate')
ax[4,].set_title('Share of Total Assets Held by the Bottom 50% ')
ax[4,].set_ylabel('Percent of Aggregate')
ax[5,].set_title('Share of Real Estate Held by the Top 1%')
ax[5,].set_ylabel('Percent of Aggregate')
ax[6,].set_title('Share of Real Estate Held by the Bottom %50')
ax[6,].set_ylabel('Percent of Aggregate')
plt.tight_layout()
plt.style.use('seaborn-white')
plt.show()

解决方法

尝试遍历所有子图并将 axvspan 添加到特定的 AxesSubplot

axes = df.plot(subplots=True,layout=(7,1),figsize=(15,15),linewidth=3.5,colormap="summer",ylabel='Percent of Aggregate',xlabel='Date')

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

plt.tight_layout()
plt.style.use('seaborn-white')
plt.show()

使用 ylabelxlabelplot kwargs 稍微减少了一些代码,并且还从 df.columns 而不是手动设置子情节标题。

plot


axvspan 添加图例。最简单的方法是为每个 axvspan 添加一个标签,并在每次迭代结束时制作图例:

axes = df.plot(subplots=True,xlabel='Date',legend=False)

for (ax,alpha=0.5,label='2008 Crisis')
    ax.axvspan('2019-12-1',label='Pandemic')
    ax.set_title(col)
    ax.legend()

plt.style.use('seaborn-white')
plt.tight_layout()
plt.show()

plot 2 with axvspan legend on all subplots


或者,可以只为危机制作一个图例:

fig,axes = plt.subplots(nrows=7,15))
df.plot(subplots=True,ax=axes,xlabel='Date')

for ax,label='Pandemic')
    ax.set_title(col)

handles,labels = axes[-1].get_legend_handles_labels()

fig.legend(handles[-2:],labels[-2:],title='Crises',loc='lower left',ncol=2)

plt.style.use('seaborn-white')
plt.tight_layout()
plt.show()

plot 3 single legend for Crises

^ 单个图例位于左下方。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?