第一章 使用 matplotlib 绘制折线图
第二章 使用 matplotlib 绘制条形图
第三章 使用 matplotlib 绘制直方图
第四章 使用 matplotlib 绘制散点图
第五章 使用 matplotlib 绘制饼图
第六章 使用 matplotlib 绘制热力图
第七章 使用 matplotlib 绘制堆叠条形图
第八章 使用 matplotlib 在一个画布内绘制多个图
上一章我们讲述了热力图的绘制,本章我们来讲述堆叠条形图的绘制。
堆叠条形图是一种用来分解整体、比较各部分的图。与条形图类似,堆叠条形图常被用于比较不同类别的数值。而且,它的每一类数值内部,又被划分为多个子类别,这些子类别一般用不同的颜色来表示。
如果说条形图可以帮助我们观察总量,那么堆叠条形图则可以同时反映总量与结构,即总量是多少?它又是由哪些部分构成的?进而,我们还可以探究哪一部分比例最大,以及每一部分的变动情况等等。
堆叠条形图的绘制和条形图类似,同样是调用 bar 函数,只不过在参数设置时稍有区别,示例代码如下:
# importing package import matplotlib.pyplot as plt import numpy as np plt.style.use('fivethirtyeight') x = ['A', 'B', 'C', 'D'] y1 = np.array([10, 20, 10, 30]) y2 = np.array([20, 25, 15, 25]) y3 = np.array([12, 15, 19, 6]) y4 = np.array([10, 29, 13, 19]) plt.bar(x, y1, label='Round1', width=0.67) plt.bar(x, y2, bottom=y1, label='Round2', width=0.67) plt.bar(x, y3, bottom=y1+y2, label='Round3', width=0.67) plt.bar(x, y4, bottom=y1+y2+y3, label='Round4', width=0.67) plt.xlabel("Teams") plt.ylabel("Score") plt.legend() plt.title("Scores by Teams in 4 Rounds") plt.tight_layout() plt.show()
在上面的代码中,列表 x 代表 4 只队伍,列表 y1、y2、y3 和 y4 分别表示 4 只队伍在 4 局比赛的得分。在进行图形绘制时,在绘制 y2 数据时,设置 bottom = y1,意思是在 y1 数据绘制的条形图的基础进行绘制,也就是形成堆叠图。代码执行完得到的图形如下图所示:
import matplotlib.pyplot as plt import numpy as np plt.style.use('fivethirtyeight') x = ['A', 'B', 'C', 'D'] y1 = np.array([10, 20, 10, 30]) y2 = np.array([20, 25, 15, 25]) y3 = np.array([12, 15, 19, 6]) y4 = np.array([10, 29, 13, 19]) plt.barh(x, y1, label='Round1', height=0.67) plt.barh(x, y2, left=y1, label='Round2', height=0.67) plt.barh(x, y3, left=y1+y2, label='Round3', height=0.67) plt.barh(x, y4, left=y1+y2+y3, label='Round4', height=0.67) plt.xlabel("Score") plt.ylabel("Teams") plt.legend() plt.title("Scores by Teams in 4 Rounds") plt.tight_layout() plt.show()
在绘制水平方向的堆叠条形图时,需要将参数 bottom 改为 left,将参数 width 改为 height,需要将 x 轴标签改为 Score,y 轴标签改为 Teams。其他的和垂直方向的堆叠条形图的绘制类似。代码执行后得到的图形如下图所示:
import matplotlib.pyplot as plt import numpy as np plt.style.use('fivethirtyeight') x = ['A', 'B', 'C', 'D'] y1 = np.array([10, 20, 10, 30]) y2 = np.array([20, 25, 15, 25]) y3 = np.array([12, 15, 19, 6]) y4 = np.array([10, 29, 13, 19]) plt.barh(x, y1, label='Round1', height=0.67) plt.barh(x, y2, left=y1, label='Round2', height=0.67) plt.barh(x, y3, left=y1+y2, label='Round3', height=0.67) plt.barh(x, y4, left=y1+y2+y3, label='Round4', height=0.67) plt.xlabel("Score") plt.ylabel("Teams") plt.legend(loc='lower right') plt.title("Scores by Teams in 4 Rounds") plt.tight_layout() plt.show()
在上面的代码中,我们通过设置 legend 函数的 loc 参数来改变图例的位置。
对比不同类别数据的数值大小,同时对比每一类别数据中,子类别的构成及大小。
本章我们讲了堆叠条形图的绘制以及堆叠条形图的适用场景和不适用场景。
联系客服