【发布时间】:2021-07-18 15:54:34
【问题描述】:
我是matplotlib 的新用户。我已经学习了在 matplotlib 中绘制数据的基础知识。但我仍然无法理解如何绘制多个时间序列数据,如下所示:
情节包含一个传奇对我来说也很重要。
数据举例:
import pandas as pd
from io import StringIO
from matplotlib import pyplot as plt
data_str = '''time x1 x2 x3 x4
01.01.1984 100 -50 50 54
01.02.1984 200 -20 180 7
01.03.1984 250 -100 150 442413
01.04.1984 300 -50 250 7
01.05.1984 250 -150 100 403
01.06.1984 300 -200 100 148
01.07.1984 200 -100 100 1096'''
df = pd.read_csv(StringIO(data_str), delim_whitespace=True)
df['time'] = pd.to_datetime(df['time'], format='%d.%m.%Y')
df = df.set_index('time')
ax = df['x3'].plot(grid=True, figsize=(10, 6), color='tab:grey', linewidth=4)
ax.bar(height=df['x1'], x=df.index, color='tab:blue', width=0.3, zorder=2, label='x1')
ax.bar(height=df['x2'], x=df.index, color='tab:orange', width=0.3, zorder=2, label='x2')
ax2 = ax.twinx()
ax2.set_yscale('log')
ax2.invert_yaxis()
df['x4'].plot.line(ax=ax2, color='gold', label='x4 (right)', linewidth=4)
ax.axhline(linewidth=1, color='black')
ax.set_xlabel('time', fontsize=16)
plt.xticks(size = 16)
plt.yticks(size = 16)
handles1, labels1 = ax.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
handles = handles1[1:] + handles1[:1] + handles2 # handles1 is reordered because it uses the line before the bars
labels = labels1[1:] + labels1[:1] + labels2
#order = [0,1,2,3]
ax.legend([handles[idx] for idx in order],[labels[idx] for idx in order],
loc='upper center', bbox_to_anchor=(0.5, -0.2),
fancybox=True, shadow=True, ncol=5,
prop={'size': 16})
#plt.xlim(['1983-12-01', '1984-08-01'])
plt.show()
【问题讨论】:
标签: python python-3.x matplotlib time-series data-visualization