import numpy as np
import matplotlib.pyplot as plt
# 数据
x = np.arange(1, 6)
y1 = [1, 3, 4, 2, 5]
y2 = [2, 4, 1, 3, 2]
y3 = [3, 2, 3, 1, 4]
# 绘图
plt.stackplot(x, y1, y2, y3, labels=['A', 'B', 'C'], colors=['#FF1493', '#00FFFF', '#FFFF00'])
plt.legend(loc='upper left')
plt.title('Rainbow Stacked Area Chart')
plt.xlabel('X')
plt.ylabel('Y')
# 显示图表
plt.show()
虽然颜色非常分明,但是略感刺眼,可以把颜色调整得更加柔和一点。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
# 数据
x = np.arange(1, 6)
y1 = [1, 3, 4, 2, 5]
y2 = [2, 4, 1, 3, 2]
y3 = [3, 2, 3, 1, 4]
# 渐变颜色
cmap = plt.get_cmap('Blues')
gradient_colors = [colors.to_hex(cmap(i/3)) for i in range(3)]
# 绘图
plt.stackplot(x, y1, y2, y3, labels=['A', 'B', 'C'], colors=gradient_colors)
plt.legend(loc='upper left')
plt.title('Gradient Stacked Area Chart')
plt.xlabel('X')
plt.ylabel('Y')
# 显示图表
plt.show()
调整颜色后明显更加美观,插入到ppt或者论文中都是毫无问题的。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
# 创建数据
x = np.linspace(0, 5, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.exp(x/5)
# 创建堆叠面积图
cmap = cm.get_cmap('Spectral')
plt.stackplot(x, y1, y2, y3, labels=['Sin(x)', 'Cos(x)', 'Exp(x/5)'], colors=[cmap(0.2), cmap(0.5), cmap(0.8)], alpha=0.7)
plt.legend(loc='upper left')
# 添加标题和标签
plt.title('Stacked Area Chart')
plt.xlabel('X')
plt.ylabel('Y')
# 显示图表
plt.show()