【问题标题】:Year and month colorbar plots in Python and PandasPython 和 Pandas 中的年月彩条图
【发布时间】:2021-03-16 02:37:06
【问题描述】:

我正在绘制 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 年。我怎么得到这个?

【问题讨论】:

标签: python pandas dataframe matplotlib colorbar


【解决方案1】:

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

产生:

【讨论】:

  • 这有效地回答了我的问题。是的!我删除了浮点计算,这是不必要的。你的彩色条形码确实帮助我实现了我想要的。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 2017-04-06
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多