[英]Day of year format x axis 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')
您的问题很明确,您应该发布数据框以及正在处理的数据的样本。 您可以使用此行代码选择在x轴上的刻度线的位置。
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.