python - 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 年。我怎么得到这个?
解决方案
不确定我是否正确理解了您的问题,尤其是关于您要求“根据月份和样本来源为栏着色”。另外,我不确定您为什么要在这里尝试将时间戳转换为浮点数: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()
产生:
推荐阅读
- azure - Azure SQL 中的“用户登录失败”为“打开时底层提供程序失败”
- amazon-web-services - 如果收到消息,AWS SQS 长轮询是否会提前返回?
- reactjs - 通过键过滤对象的对象
- spring - 在spring boot中每月自动创建带有后缀的实体
- x86-64 - 带 SSE 的 8 位 LERP
- java - 构建 Java netty SslContext 和 apache SSLContexts 以信任来自动态 .pem 文件的证书,而无需预加载信任库
- javascript - Chrome/Safari 基本测试:使用 IP 地址而不是 localhost 时,CSS、Javascript、图像不起作用,因为它正在“https”中查找文件
- google-apps-script - 在 Google Appscript 中抓取具有特定文件名的多个附件
- python - 无论如何我可以使输出更易于阅读,Reading Data from 1000+ JSON files
- python - 使用数组作为多变量函数的输入