【问题标题】:python - How to plot data with repeating x axispython - 如何用重复的x轴绘制数据
【发布时间】:2018-10-03 01:36:02
【问题描述】:

我想绘制多年的日相关数据,其中年份应该在 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 年的数据依次绘制,而不是彼此重叠

【问题讨论】:

  • 嗨@Shaun,你能把你到目前为止尝试过的东西贴出来吗?您能否将示例数据添加到您的代码中,以便人们更容易帮助您?您的问题现在看起来有点过于宽泛,无法得到一个好的答案......
  • @toti08 嗯好的...我认为如果有办法重复 x 轴并为其分配数据,这更像是一个概念性问题。但我会在问题中添加一些代码

标签: python matplotlib


【解决方案1】:

你有一个字典

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

【讨论】:

  • 这是一种非常好的绘制数据的方法。 L_B_1 是一个字典,所以我得到这个:AttributeError:'dict' object has no attribute 'yearday'。我的代码也绘制了数据。但是,我希望 2016 年的所有数据超过 365 天,然后超过 2017 年的新 365 天数据等...我认为您的代码与我的代码绘制相同:) 并不是我想要的.
  • 我几乎认为它会变成这样,因为我没有完全理解您拥有哪种变体以及您想要实现哪种变体。而且我也不在乎你有一个 dict 的事实 - 对不起......我会编辑......
猜你喜欢
  • 2021-12-09
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 2019-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多