python-如何使用重复的x轴绘制数据

时间:2018-10-02 07:07:46

标签: python matplotlib

我想绘制多年以来与日相关的数据,其中年份应在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年的数据,而不是一个个地叠加

1 个答案:

答案 0 :(得分:0)

You have a dict

L_B_1_mean 

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

plot using pandas:

import pandas as pd

You can simply create a pandas series from this dict:

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

...and cast the strings in the index to dates:

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

Then you can plot your data easily:

s.plot(marker='o')

enter image description here

plot using datetime and 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')