从零开始:创建百分比堆积柱状图、簇形柱状图和并列子图

作者:渣渣辉2024.01.17 22:10浏览量:34

简介:在这篇文章中,我们将学习如何使用Python的matplotlib库来绘制百分比堆积柱状图、簇形柱状图和并列子图。我们将从数据准备开始,然后逐步讲解如何创建这些图表。

在Python中,我们通常使用matplotlib库来创建各种数据可视化图表。以下是如何使用matplotlib来创建百分比堆积柱状图、簇形柱状图和并列子图的步骤。
首先,确保你已经安装了matplotlib库。如果没有,你可以使用pip来安装:

  1. pip install matplotlib

百分比堆积柱状图
百分比堆积柱状图是一种展示各类别数据所占比例的图表。以下是一个简单的例子:

  1. import matplotlib.pyplot as plt
  2. # 假设我们有以下数据
  3. data = [20, 35, 30, 35, 27]
  4. labels = ['A', 'B', 'C', 'D', 'E']
  5. # 计算每个类别的百分比
  6. percentages = [data[i]/sum(data) * 100 for i in range(len(data))]
  7. # 绘制柱状图
  8. plt.bar(labels, percentages, color=['blue', 'green', 'red', 'yellow', 'purple'])
  9. plt.xlabel('Labels')
  10. plt.ylabel('Percentage')
  11. plt.title('Percentage Stacked Bar Chart')
  12. plt.show()

簇形柱状图
簇形柱状图是一种展示不同类别数据之间比较的图表。以下是一个简单的例子:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 假设我们有以下数据
  4. categories = ['A', 'B', 'C', 'D', 'E']
  5. values1 = [20, 35, 30, 35, 27]
  6. values2 = [25, 32, 34, 20, 25]
  7. # 绘制柱状图
  8. plt.bar(categories, values1, color='blue')
  9. plt.bar(categories, values2, color='red', bottom=values1)
  10. plt.xlabel('Categories')
  11. plt.ylabel('Values')
  12. plt.title('Clustered Bar Chart')
  13. plt.show()

并列子图
并列子图是一种展示多个相关数据系列的图表。以下是一个简单的例子:
```python
import matplotlib.pyplot as plt
import numpy as np

假设我们有以下数据

x = np.arange(5) # x values from 0 to 4
y1 = [20, 35, 30, 35, 27] # y values for the first series
y2 = [25, 32, 34, 20, 25] # y values for the second series
labels = [‘Series1’, ‘Series2’] # labels for the series

绘制子图

plt.subplot(1, 2, 1) # Create a subplot with 1 row and 2 columns. The first plot is in the first column.
plt.bar(x, y1) # Plot the first series of data using blue bars.
plt.xlabel(‘Categories’) # Set x-axis label. Remove this line if you already set the label using plt.bar().xlabel().
plt.ylabel(‘Values’) # Set y-axis label. Remove this line if you already set the label using plt.bar().ylabel().
plt.title(‘Bar Chart (Side by Side)’) # Set the title of the plot. Remove this line if you already set the title using plt.bar().title().
plt.xticks(x, labels) # Set x-axis tick marks and labels. Remove this line if you already set the ticks using plt.bar().xticks().
plt.legend([‘Series1’]) # Add legend with the series names. Remove this line if you already set the legend using plt.bar().legend().
plt.subplot(1, 2, 2) # Create another subplot in the second column. This is done with plt.subplot(). It uses the syntax (nrows, ncols, index). Here nrows=1 and ncols=2 and index=2 for the second plot. Change these values to create different layouts for your subplots. You can also use plt.sub