使用Python生成多维度的堆叠柱状图
发布时间:2023-12-12 04:53:07
堆叠柱状图是一种可视化多个维度数据的有效方法。在Python中,我们可以使用matplotlib库生成多维度的堆叠柱状图。下面是一个生成多维度的堆叠柱状图的例子:
假设我们有一个数据集,包含三个城市(纽约、洛杉矶、芝加哥)的销售额和利润数据,我们希望通过堆叠柱状图来比较它们之间的销售额和利润情况。
首先,我们需要导入所需的库:
import matplotlib.pyplot as plt import numpy as np
接下来,我们定义城市的名称和各自的销售额和利润数据:
cities = ['New York', 'Los Angeles', 'Chicago'] sales = [800000, 600000, 700000] profits = [400000, 300000, 200000]
然后,我们创建一个表示X轴位置的numpy数组,并计算每个城市的利润占销售额的比例:
x = np.arange(len(cities)) profit_percentage = [profit / sale * 100 for profit, sale in zip(profits, sales)]
接下来,我们使用matplotlib库的bar函数绘制堆叠柱状图,其中利润占比作为每个城市的底部,销售额占比作为每个城市的顶部:
plt.bar(x, profits, label='Profit') plt.bar(x, sales, bottom=profits, label='Sales')
我们使用xticks函数设置X轴刻度标签为城市名称,并对图例进行设置:
plt.xticks(x, cities) plt.legend()
最后,我们使用show函数显示生成的图形:
plt.show()
完整代码如下:
import matplotlib.pyplot as plt import numpy as np cities = ['New York', 'Los Angeles', 'Chicago'] sales = [800000, 600000, 700000] profits = [400000, 300000, 200000] x = np.arange(len(cities)) profit_percentage = [profit / sale * 100 for profit, sale in zip(profits, sales)] plt.bar(x, profits, label='Profit') plt.bar(x, sales, bottom=profits, label='Sales') plt.xticks(x, cities) plt.legend() plt.show()
运行以上代码,我们将得到一个带有堆叠柱状图的图形,其中每个城市的销售额和利润都被表示为堆叠在一起的柱子,利润占比显示为每个城市柱子的底部,销售额占比显示为顶部。
这个例子演示了如何使用Python生成多维度的堆叠柱状图。您可以根据自己的数据和需求进行相应的修改和定制,以生成适合自己的堆叠柱状图。
