首页 > 解决方案 > Python 和 Pandas 中的年月彩条图

问题描述

我正在绘制 400 天的数据。1个样本代表1天,共400个样本。我想根据月份和样本的来源为条形着色。

代码:

df = 
timestamp                y_val
2019-10-01 08:10:53    0.620505
2019-11-01 08:10:57    0.720505
2019-12-01 08:10:59    0.820505
2020-01-01 08:11:02    0.920505
2020-02-01 08:11:06    0.520505
2020-03-14 13:05:22    0.629888
2020-04-14 13:05:25    0.729888
2020-05-14 13:05:27    0.829888
2020-06-14 13:05:31    0.929888
2020-07-14 13:05:33    0.429888

plt.scatter(df.index,df['y_val'],
            c=df.index.year+df.index.month/12,cmap='jet_r')
plt.colorbar()
plt.show()

输出:

在此处输入图像描述

它看起来不错,但问题是彩条的外观。很难说它是在谈论年份和月份。至少,我想在那里看到 2019 年和 2020 年。我怎么得到这个?

标签: pythonpandasdataframematplotlibcolorbar

解决方案


不确定我是否正确理解了您的问题,尤其是关于您要求“根据月份和样本来源为栏着色”。另外,我不确定您为什么要在这里尝试将时间戳转换为浮点数:df.index.year+df.index.month/12.

由于您的 x 轴已经为您提供日期信息,我不太确定您为什么要在颜色栏上添加相同的信息;但是,也许我只是误解了您的要求。

无论如何,请尝试以下代码:

import pandas as pd
from io import StringIO
import matplotlib.pyplot as plt

raw="""
timestamp                y_val
2019-10-01 08:10:53    0.620505
2019-11-01 08:10:57    0.720505
2019-12-01 08:10:59    0.820505
2020-01-01 08:11:02    0.920505
2020-02-01 08:11:06    0.520505
2020-03-14 13:05:22    0.629888
2020-04-14 13:05:25    0.729888
2020-05-14 13:05:27    0.829888
2020-06-14 13:05:31    0.929888
2020-07-14 13:05:33    0.429888"""

df = pd.read_csv(StringIO(raw),delimiter=" \s+",index_col=0, engine="python")
df.index = pd.to_datetime(df.index)

fig,ax=plt.subplots()
sca = ax.scatter(df.index,df['y_val'],c=df.index,cmap='jet_r')
cbar = plt.colorbar(sca)

cbar.ax.set_yticklabels(pd.to_datetime(cbar.get_ticks()).strftime(date_format='%b %Y'))

fig.autofmt_xdate()
plt.show()

产生:

使用日期格式的颜色条绘图


推荐阅读