结果显示:
代码如下:
# 面积(堆积折线图):stackplot
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
# 生成数据
x = np.linspace(0, 20, 20)
y1 = np.random.randint(50, 100, 20)
y2 = np.random.randint(50, 100, 20)
y3 = np.random.randint(50, 100, 20)
# 堆积条形图
plt.barh(x, y1, color='y', label='语文')
plt.barh(x, y2, left=y1, color='g', label='数学')
plt.barh(x, y3, left=y1 + y2, color='c', label='英语')
# 显示范围
plt.ylim(-2, 22)
plt.xlim(0, 280)
# 添加图例
plt.legend(loc='upper right')
plt.grid(axis='x', color='grey', linestyle=':', linewidth=1)'''
# 堆叠折线图
y1p = y1 / (y1 + y2 + y3)
y2p = y2 / (y1 + y2 + y3)
y3p = y3 / (y1 + y2 + y3)
plt.subplot(1, 2, 1)
plt.stackplot(x, y1, y2, y3, baseline='zero', labels=[
'语文', '数学', '英语'], colors=['y', 'g', 'c'])
plt.xlim(0, 22)
plt.ylim(0, 280)
plt.legend(loc='upper right')
plt.grid(axis='y', color='grey', linestyle=':', linewidth=1)
plt.subplot(1, 2, 2)
plt.stackplot(x, y1p, y2p, y3p, baseline='zero', labels=[
'语文', '数学', '英语'], colors=['y', 'g', 'c'])
plt.xlim(0, 20)
plt.ylim(0, 1)
plt.legend(loc='upper right')
plt.grid(axis='y', color='grey', linestyle=':', linewidth=1)
plt.show()