![](/img/trans.png)
[英]how to make a plot by repeating strings on x-axis in matplotlib?
[英]python - How to plot data with repeating x axis
我想繪制多年應該依賴於天的數據,其中年份應該在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年的數據,彼此之后而不是彼此疊加
你有一個命令
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.