python - 一年中的日期格式 x 轴 matplotlib
问题描述
我有一个带有累积降雨数据的熊猫数据框。
列是'dayoftheyear', '1981', '1982' .... '2019'
我使用以下代码绘制数据:
fig, ax = plt.subplots(1, 1, figsize=(10,10))
ax.set_title('Cummulative rainfall in Chennai hydrological basin')
ax.set_xlabel('day of the year')
ax.set_ylabel('total rainfall in mm')
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
df.plot(ax=ax,
x='dayofyear',
y=years_string,
colormap='gray',
legend=False,
alpha=0.2)
df.plot(ax=ax,
x='dayofyear',
y=['2015','2016','2017','2018'],
alpha=0.7,
colormap='plasma')
df.plot(ax=ax,
x='dayofyear',
y='2019',
color='red',
linewidth=3)
fig.savefig('test.jpg')
然而,一年中的哪一天可能很难理解,如果可能的话,我想每月添加主要的刻度线和当月的哪一天。我找到了这个资源并试图让它工作无济于事。有没有一种简单的方法可以在不转换数据的情况下更改 xaxis 刻度?
完整代码在这里
解决方案
回答我自己的问题。
最简单的解决方案是转换为日期时间。使用格式页面设置轴的绘图
# -*- coding: utf-8 -*-
"""Y2019M07D31_RH_Chennai_v01.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/gist/rutgerhofste/666c1a01e9f2724de1451ee9b27d9cdd/y2019m07d31_rh_chennai_v01.ipynb
"""
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.dates as dates
df =pd.read_csv('https://gist.githubusercontent.com/rutgerhofste/94b9035bdcaf1163ff910a08ad3239a3/raw/db2efe21aa980418558010695db08af5c27b616c/cummulative.csv')
df.head()
df['date'] = pd.to_datetime(df['dayofyear'], format='%j')
years = list(range(1981,2014+1))
def string(year):
return str(year)
years_string = list(map(string,years))
fig, ax = plt.subplots(1, 1, figsize=(10,10))
ax.set_title('Cummulative rainfall in Chennai hydrological basin')
df.plot(ax=ax,
x='date',
y=years_string,
colormap='gray',
legend=False,
alpha=0.2)
df.plot(ax=ax,
x='date',
y=['2015','2016','2017','2018'],
alpha=0.7,
colormap='viridis')
df.plot(ax=ax,
x='date',
y='2019',
color='red',
linewidth=3)
ax.set_xlabel('Month')
ax.set_ylabel('total rainfall in mm')
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
major_format = mdates.DateFormatter('%b')
ax.xaxis.set_major_formatter(major_format)
ax.xaxis.grid(linestyle=':')
fig.savefig('test.pdf')
推荐阅读
- web-scraping - 谷歌表格的网页抓取
- mysql - 尝试使用 Debezium 从 MYSQL 中提取数据会出错
- javascript - 如何并行生成五个子进程
- c# - 将 Pact 合约测试从 JavaScript 重写为 C#
- javascript - 从 Node.js 中的 Gmail Api 直接将 base64 编码的 PDF 解码为字符串
- security - 在 Cloud Run vs Compute Engine 中存储为环境变量的敏感信息
- angular - chartjs 角度更新顺序
- android-jetpack-compose - Jetpack 是否为 LazyColumnFor/LAazyRowFor 发布 onClickListener?
- bootstrap-4 - 引导表单验证仅在重新加载页面后在 nuxt.js 中有效
- maven - Gitlab maven 部署到包注册表