Python 蟒蛇和熊猫的年和月色条图

Python 蟒蛇和熊猫的年和月色条图,python,pandas,dataframe,matplotlib,colorbar,Python,Pandas,Dataframe,Matplotlib,Colorbar,我正在绘制400天的数据。一个样本代表一天,总共400个样本。我想根据月份和样本来源为条形图上色 代码: 输出: 它看起来不错,但问题是颜色条的外观。很难说它是在谈论年和月。至少,我想看到2019年和2020年。我怎么知道的?不确定我是否正确理解了您的问题,尤其是关于您要求“根据月份和样本来源为条形图上色”的问题。另外,我不知道为什么要在这里尝试将时间戳转换为浮点:df.index.year+df.index.month/12 由于您的x轴已经为您提供了日期信息,我不太确定您为什么要在颜色栏上

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

代码:

输出:


它看起来不错,但问题是颜色条的外观。很难说它是在谈论年和月。至少,我想看到2019年和2020年。我怎么知道的?

不确定我是否正确理解了您的问题,尤其是关于您要求“根据月份和样本来源为条形图上色”的问题。另外,我不知道为什么要在这里尝试将时间戳转换为浮点:
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()
这将产生:


这是否回答了您的问题@阿斯莫斯:这并没有回答我的问题。我的df有时间戳(日期+时间)。我在颜色栏中得到了奇怪的结果,比如(1970年1月)。这有效地回答了我的问题。对我删除了不必要的浮点计算。你的彩色条形码确实帮助我实现了我的愿望。非常感谢。
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()