实现功能:
python绘制双坐标系(双变量)时间序列图。
实现代码:
1 | import pandas as pd |
2 | import numpy as np |
3 | import matplotlib.pyplot as plt |
4 | |
5 | # Import Data |
6 | df = pd.read_csv("F:\数据杂坛\datasets\economics.csv") |
7 | |
8 | x = df['date'] |
9 | y1 = df['psavert'] |
10 | y2 = df['unemploy'] |
11 | |
12 | # Plot Line1 (Left Y Axis) |
13 | fig, ax1 = plt.subplots(1, 1, figsize=(12, 6), dpi=100) |
14 | ax1.plot(x, y1, color='tab:red') |
15 | |
16 | # Plot Line2 (Right Y Axis) |
17 | ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis |
18 | ax2.plot(x, y2, color='tab:blue') |
19 | |
20 | # Decorations |
21 | # ax1 (left Y axis) |
22 | ax1.set_xlabel('Year', fontsize=18) |
23 | ax1.tick_params(axis='x', rotation=70, labelsize=12) |
24 | ax1.set_ylabel('Personal Savings Rate', color='#dc2624', fontsize=16) |
25 | ax1.tick_params(axis='y', rotation=0, labelcolor='#dc2624') |
26 | ax1.grid(alpha=.4) |
27 | |
28 | # ax2 (right Y axis) |
29 | ax2.set_ylabel("Unemployed (1000's)", color='#01a2d9', fontsize=16) |
30 | ax2.tick_params(axis='y', labelcolor='#01a2d9') |
31 | ax2.set_xticks(np.arange(0, len(x), 60)) |
32 | ax2.set_xticklabels(x[::60], rotation=90, fontdict={'fontsize': 10}) |
33 | ax2.set_title( |
34 | "Personal Savings Rate vs Unemployed: Plotting in Secondary Y Axis", |
35 | fontsize=18) |
36 | fig.tight_layout() |
37 | plt.show() |
实现效果:
喜欢记得点赞,在看,收藏,
关注V订阅号:数据杂坛,获取数据集,完整代码和效果,将持续更新!
| 留言与评论(共有 0 条评论) “” |