Python 年月日格式x轴matplotlib
我有一个包含累积降雨数据的熊猫数据框 这些列是Python 年月日格式x轴matplotlib,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有一个包含累积降雨数据的熊猫数据框 这些列是“年度日期”、“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') a
“年度日期”、“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刻度
完整代码您的问题很清楚,您应该发布一个数据帧示例以及您正在处理的内容。您可以使用这行代码在x轴上选择记号的位置
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
回答我自己的问题 最简单的解决方案是转换为datetime。使用设置轴的打印
您可以将dayofyear列转换为true dates。这里有一个指向完整脚本的链接,其中包括数据和示例
# -*- 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')