Python draws a stacked histogram


本文详细介绍如何使用 Matplotlib 绘制柱状堆叠图


1. Import library

import matplotlib.pyplot as plt
import numpy as np

2. Data preparation

Example: pandas is a NumPy-based tool created to solve data analysis tasks.
Before we can start plotting a stacked column chart, we need to generate experimental data. In this case, we can use the NumPy library to generate two arrays y1 and y2 to represent the sales of products A and B in five different cities, respectively. code show as below:

import numpy as np

# 生成实验数据
x = np.array(['A', 'B', 'C', 'D', 'E'])
y1 = np.array([12, 25, 19, 23, 20])
y2 = np.array([15, 24, 25, 18, 20])

3. Draw a basic columnar stacked chart

1. Draw basic graphics

Use Matplotlib's bar function to draw a stacked bar chart. This function needs to pass in the following parameters:

  1. left: the left position of each rectangle;
  2. height: the height of each rectangular bar;
  3. bottom: the position of the bottom edge of each rectangle, that is, the position of the top of the previous rectangle;
  4. width: the width of each rectangular bar, the value is 0.8 by default.

Use two arrays y1 and y2 to represent the sales of products A and B in five cities respectively, and use an x ​​array to represent the names of each city. Let's first define a drawing parameter about the histogram, the code is as follows:

# 设置字体样式和大小
font={
    
    'family':'Times New Roman','size':28}
font_value = {
    
    'family':'Times New Roman','size':20}

# 绘制柱状堆叠图,设置柱子颜色和标签
fig, ax = plt.subplots(figsize=(12, 8))
N = len(y1)
width = 0.45
ind = np.arange(N)

bar_plot1 = ax.bar(ind, y1, width, color=plt.cm.Set1(np.arange(N)), alpha=0.7, label='Type A')
bar_plot2 = ax.bar(ind, y2, width, bottom=y1, color=plt.cm.Set2(np.arange(N)), alpha=0.7, label='Type B')

insert image description here

2. Set column width, add scale label and rotation angle

Adjust the width of the columns so that there is a larger distance between them to more clearly distinguish sales in each city.
You can use the width parameter to adjust the width of the column, for example width=0.4. Also, we need to add tick labels to the horizontal axis and rotate the labels by 45 degrees to more clearly show the name of each city. code show as below:

# 设置字体样式和大小
font={
    
    'family':'Times New Roman','size':28}
font_value = {
    
    'family':'Times New Roman','size':20}

# 绘制柱状堆叠图,设置柱子颜色和标签
fig, ax = plt.subplots(figsize=(12, 8))
N = len(y1)
width = 0.45
ind = np.arange(N)

bar_plot1 = ax.bar(ind, y1, width, color=plt.cm.Set1(np.arange(N)), alpha=0.7, label='Type A')
bar_plot2 = ax.bar(ind, y2, width, bottom=y1, color=plt.cm.Set2(np.arange(N)), alpha=0.7, label='Type B')

# 添加标题、标签和图例
ax.set_title('Sales of Product A & B in Different Cities', fontsize=24)
ax.set_xlabel('City', font)
ax.set_ylabel('Value', font)
ax.legend(ncol=2, loc='best', fontsize=20)

# 设置横坐标轴刻度标签旋转角度
new_x = ['City '+i for i in x]
plt.xticks(np.arange(len(x)), new_x, rotation=45)

# 显示图表
plt.show()


4. Complete code

import matplotlib.pyplot as plt
import numpy as np

# 生成实验数据
x = np.array(['A', 'B', 'C', 'D', 'E'])
y1 = np.array([12, 25, 19, 23, 20])
y2 = np.array([15, 24, 25, 18, 20])

# 设置字体样式和大小
font={
    
    'family':'Times New Roman','size':28}
font_value = {
    
    'family':'Times New Roman','size':2}

# 绘制柱状堆叠图,设置柱子颜色和标签
fig, ax = plt.subplots(figsize=(12, 8))
#定义绘图的柱子组数
N = len(x)
###设置柱子宽度
width = 0.45
ind = np.arange(N)

bar_plot1 = ax.bar(ind, y1, width, color=plt.cm.Set1(np.arange(N)), alpha=0.7, label='Type A')
bar_plot2 = ax.bar(ind, y2, width, bottom=y1, color=plt.cm.Set2(np.arange(N)), alpha=0.7, label='Type B')
# bar_plot3 = bar_plot2+bar_plot
# 添加标题、标签和图例
# ax.set_title('Temperature / ℃', fontsize=24)
ax.set_xlabel('City', font)
ax.set_ylabel('Value', font)
ax.legend(ncol=2, loc='best', fontsize=20)
ax.set_ylim(0,53)

##x轴刻度名称、倾斜角度
new_x = ['City '+i for i in x]
plt.xticks(np.arange(len(x)), new_x, rotation=45)
# 设置坐标轴刻度字体和字号

font_tick = {
    
    'family': 'Times New Roman', 'size': 24}
for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontproperties(font_tick)


# 调整字体颜色、柱子宽度等其他参数
for rect, height_1, height_2 in zip(bar_plot2, y1, y2):
    height_2 = rect.get_height()
    ax.text(rect.get_x() + rect.get_width()/2., height_1 + height_2 + 0.5, '%d' % int(height_2),
            ha='center', va='bottom', fontsize=20, color='green', fontname='Times New Roman')
    ax.text(rect.get_x() + rect.get_width()/2., height_1 + 1/2, '%d' % int(height_1),
            ha='center', va='bottom', fontsize=20, color='blue', fontname='Times New Roman')
   
##右上边框是否可见
# ax.spines['top'].set_visible(False)
# ax.spines['right'].set_visible(False)

##刻度线长宽设置
ax.tick_params(axis='x', direction='out', length=6, width=2)
ax.tick_params(axis='y', direction='in', length=6, width=2)

plt.tight_layout()
plt.savefig("C:/Users/ypzhao/Desktop/a.jpg",dpi=600)
# 显示图表
plt.show()

5. Running results

insert image description here

Six, python drawing previous series of article catalog

往期python绘图合集:
1. Python draws a simple line graph
2. Python reads data in excel and draws multiple subgraphs and multiple groups of graphs on one canvas
3. Python draws a histogram with error bars
4. Python draws multiple subgraphs and displays them separately
5 , Python reads excel data and draws multi-y-axis images
6, Python draws histograms and beautifies | fill columns with different colors
7, Python randomly generates data and uses double y-axes to draw two line charts with error bars
8, Python draws with errors Gradient color filling of bar charts with data annotation (advanced)
9. Python draws scatter charts | scatter point size and color depth are determined by numerical values
​​10. Matplotlib draws beautiful pie charts | python draws beautiful pie charts
11. Python reads excel data and draws
histograms and line charts with double y-axes, and the columns are filled with gradient
colors Data
14, Python draws a density map
15, Python draws a line chart with a confidence interval

Guess you like

Origin blog.csdn.net/m0_58857684/article/details/131031042