在Pandas + Matplotlib中使用Colorbar绘制时间序列 [英] Plot time series with colorbar in pandas + matplotlib

查看:52
本文介绍了在Pandas + Matplotlib中使用Colorbar绘制时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在此图表下方绘制一个颜色栏,其中颜色取决于每个时间序列的开始时间:

I'm trying to plot a colorbar below this chart, where the color depends on when each of the time series starts:

生成的用于创建绘图的代码是这样的:

The code generated to create the plot is this:

import pandas as pd
import numpy as np

import matplotlib.pyplot as plt

import seaborn as sns
sns.set()

def partial_cum_returns(start, cum_returns):
    return cum_returns.loc[start:].div(cum_returns.loc[start])

index = pd.DatetimeIndex(pd.date_range('20170101', '20190101', freq='W'))
np.random.seed(5)
returns = pd.Series(np.exp(np.random.normal(loc=0, scale=0.05, size=len(index))), index=index)
cum_returns = returns.cumprod()
df = pd.DataFrame(index=index)
for date in index:
    df[date] = partial_cum_returns(date, cum_returns)

df.plot(legend=False, colormap='viridis');
plt.colorbar();

但是执行此错误时出现:

But when executing this error appears:

RuntimeError:未找到可用于颜色条创建的可映射.首先定义一个可映射的对象,例如图像(带有imshow)或轮廓集(带有outlinef).

RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).

我试图以不同的方式添加颜色条,例如 fig,ax = plt.figure()... ,但是到目前为止,我无法使它起作用.有任何想法吗?谢谢!

I've tried to add the colorbar in different ways, like the fig, ax = plt.figure()... one, but I couldn't make it work so far. Any ideas? Thanks!

推荐答案

第一点是,您需要为颜色栏创建一个ScalarMappable.您需要定义颜色图,在您的情况下为'viridis',并指定要用于颜色条的值的最大值和最小值.然后,因为它使用数字时间值,所以您要重新格式化它们.

The first point is that you need to create a ScalarMappable for your colorbar. You need to define the colormap, which in your case is 'viridis' and specify the maximum and minimum of the values you want for the colorbar. Then because it uses numeric time values you want to reformat those.

import matplotlib.pyplot as plt
import pandas as pd

# Define your mappable for colorbar creation
sm = plt.cm.ScalarMappable(cmap='viridis', 
                           norm=plt.Normalize(vmin=df.index.min().value,
                                              vmax=df.index.max().value))
sm._A = []  

df.plot(legend=False, colormap='viridis', figsize=(12,7));

cbar = plt.colorbar(sm);
# Change the numeric ticks into ones that match the x-axis
cbar.ax.set_yticklabels(pd.to_datetime(cbar.get_ticks()).strftime(date_format='%b %Y'))

这篇关于在Pandas + Matplotlib中使用Colorbar绘制时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆