首页 > 解决方案 > 一年中的日期格式 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 刻度?

完整代码在这里

标签: pythonpandasmatplotlib

解决方案


回答我自己的问题。

最简单的解决方案是转换为日期时间。使用格式页面设置轴的绘图

# -*- 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')

在此处输入图像描述

脚本


推荐阅读