折线图与趋势表达

用折线、填充区域与文本标注呈现时间序列变化,探索数据背后的走势与故事。

折线图区域填充文本注释主题风格
美元/人民币汇率走势

图表作品

共 5 张图表 · 点击图片可放大,展开可查看完整代码

01

美元/人民币汇率走势

对比 2017 与 2019 年 7 月的汇率变化,练习颜色、线型与线宽设置。

查看 Python 代码 +
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
eurcny_2017 = np.array([6.8007,6.8060,6.7835,6.7700,6.7511,6.7265])
eurcny_2019 = np.array([6.8640,6.8881,6.8662,6.8827,6.8737,6.8841])
date_x = np.array([3,8,13,17,25,31])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(date_x, eurcny_2017, color='g',linestyle='-.',linewidth=1, label='2017年7月美元/人民币汇率')
ax.plot(date_x, eurcny_2019, color=(0.8, 0.2, 0.4), linestyle='--', linewidth=3, label='2019年7月美元/人民币汇率')
ax.set_title('2017年7月与2019年7月美元/人民币汇率走势')
ax.set_xlabel('日期')
ax.set_ylabel('汇率')
ax.legend()
plt.show()
02

季度销售额区间填充

用 fill_between 突出两条销售曲线之间的差异区域。

查看 Python 代码 +
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
sale_a = [2144,4617,7674,4409]
sale_c = [153,1214,2414,680]
x=np.arange(1,5)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,sale_a, marker='o', label='产品A')
ax.plot(x,sale_c, marker='o', label='产品C')
plt.fill_between(x,sale_a,sale_c,facecolor='#ADD8E6',alpha=0.3)
ax.set_ylabel('销售额(万元)')
ax.set_xticks(x)
ax.set_xticklabels(['第1季度','第2季度', '第3季度', '第4季度'])
ax.legend()
plt.show()
03

随机散点色彩映射

为散点赋予第三个维度(颜色),并叠加颜色条说明数值含义。

查看 Python 代码 +
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
x=np.random.rand(50)
y=np.random.rand(50)
c=np.random.rand(50)
plt.scatter(x,y,c=c,cmap='Blues',s=100)
plt.colorbar()
plt.show()
04

未来 15 天气温走势

结合文本与箭头标注,指出最高气温的极值位置并美化坐标轴。

查看 Python 代码 +
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.arange(4, 19)
y_max =[32, 33, 33, 34, 33, 31, 30, 29, 30, 29, 26, 23, 21, 25,  31]
y_min = [19, 19, 20, 22, 22, 21, 22, 16, 18, 18, 17, 14, 15, 16 , 16]
plt.plot(x, y_max, marker='^',mec='red',mfc='white', label='最高温度')
plt.plot(x, y_min, marker='o', label='最低温度')
x_temp = 4
y_h =34
plt.text(x_temp-0.3, y_h  + 0.7, y_h, family='SimHei', fontsize=8, fontstyle='normal')
plt.annotate("最大气温",xy=(7,34),xytext=(8,36),fontfamily='serif',fontweight='bold',arrowprops=dict(arrowstyle='->'))
plt.title('未来15天最高气温和最低气温的走势')
plt.xlabel('日期')
plt.ylabel(r'温度($^\circ$C)')
plt.ylim(0, 40)
plt.legend()
plt.show()
05

ggplot 风格二次函数

切换绘图主题样式,用 ggplot 风格呈现抛物线。

查看 Python 代码 +
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.style.use('ggplot')
x = np.linspace(-5, 5, 100)
y = x ** 2
plt.plot(x, y,label='$y=x^2$')
plt.title('使用ggplot主题风格的折线图')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()