【问题标题】:Plot time series with colorbar in pandas + matplotlib在 pandas + matplotlib 中用颜色条绘制时间序列
【发布时间】:2018-07-03 18:12:16
【问题描述】:

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

用于创建绘图的代码如下:

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();

但是执行的时候出现这个错误:

RuntimeError: 找不到可用于创建颜色条的可映射对象。首先定义一个可映射对象,例如图像(使用 imshow)或轮廓集(使用 contourf)。

我尝试以不同的方式添加颜色条,例如 fig, ax = plt.figure()... 之一,但到目前为止我无法让它工作。有任何想法吗?谢谢!

【问题讨论】:

    标签: python pandas matplotlib data-visualization


    【解决方案1】:

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

    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'))
    

    【讨论】:

    • 谢谢!我使用此代码使颜色条水平:cbar = plt.colorbar(sm, orientation='horizontal', pad=0.1, aspect=40, shrink=0.9);
    • 另外,sm._A = [] 行在你的代码中做了什么?
    • @XoelLópezBarata 据我所知,可映射对象需要一个数组。以我所做的方式初始化标量可映射将其数组初始化为None,这导致TypeError: You must first set_array for mappable。该行只是将数组设置为空列表。虽然我不确定你会用它做什么。对彩条有更多专业知识的人可以回答这个问题。
    • @Xoel 你找到解决方案了吗?我现在也遇到了同样的问题
    猜你喜欢
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2017-10-08
    • 2016-03-14
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多