首页 > 解决方案 > python - 如何用重复的x轴绘制数据

问题描述

我想绘制多年的日相关数据,其中年份应该在 x 轴上(例如 2016、2017、2018)。这样做的好方法是什么?

对于每一年,我都有一个日期列表,我会在 x 轴上绘制,但当然 python 会保留这个轴并将不同年份的所有数据相互绘制。

有什么建议么?

代码:

我的字典的缩短版本 L_B_1_mean如下所示:

2016018 5.68701407589
2016002 4.72437644462
2017018 3.39389424822
2018034 7.01093439059
2018002 8.79958946488
2017002 3.55897852367

编码:

data_plot = {"x":[], "y":[], "label":[]}
for label, coord in L_B_1_mean.items():
    data_plot["x"].append(int(label[-3:]))             
    data_plot["y"].append(coord)
    data_plot["label"].append(label)


# add labels
for label, x, y in zip(data_plot["label"], data_plot["x"], data_plot["y"]):
    axes[1].annotate(label, xy = (x, y+0.02), ha= "left")


# 1 channel different years Plot
plt_data = axes[1].scatter(data_plot["x"], data_plot["y"])

我在这里构建我的 x 值:data_plot["x"].append(int(label[-3:]))我在其中读取名称标签,例如:2016002 并仅获取日期值:002

最后,我每年有 365 天,现在我想将 2016 年、2017 年和 2018 年的数据依次绘制,而不是彼此重叠

标签: pythonmatplotlib

解决方案


你有一个字典

L_B_1_mean 

{'2016018': 5.68701407589,
 '2016002': 4.72437644462,
 '2017018': 3.39389424822,
 '2018034': 7.010934390589999,
 '2018002': 8.79958946488,
 '2017002': 3.55897852367}

使用熊猫绘图:

import pandas as pd

你可以简单地从这个字典创建一个熊猫系列:

s = pd.Series(L_B_1_mean)

2016018    5.687014
2016002    4.724376
2017018    3.393894
2018034    7.010934
2018002    8.799589
2017002    3.558979
dtype: float64

...并将索引中的字符串转换为日期:

s.index = pd.to_datetime(s.index, format='%Y%j')

2016-01-18    5.687014
2016-01-02    4.724376
2017-01-18    3.393894
2018-02-03    7.010934
2018-01-02    8.799589
2017-01-02    3.558979
dtype: float64

然后您可以轻松地绘制数据:

s.plot(marker='o')

在此处输入图像描述

使用 datetime 和 matplotlib 绘图:

import datetime as DT
import matplotlib.pyplot as plt

t = [DT.datetime.strptime(k, '%Y%j') for k in L_B_1_mean.keys()]
v = list(L_B_1_mean.values())

v = sorted(v, key=lambda x: t[v.index(x)])
t = sorted(t)

plt.plot(t, v, 'b-o')

推荐阅读