Python draws a histogram with error bars and gradient color filling with data annotation (advanced)

往期python绘图合集:
python draws a simple line chart
python reads data in excel and draws multiple subgraphs and multiple groups of graphs on one canvas
python draws a histogram with error bars
python draws multiple subgraphs and displays them separately
python reads excel data and draws multiple y Axis image
python draws histogram and beautifies | fills the columns with different colors



Prepare data

提示:这里可以添加本文要记录的大概内容:

This article mainly introduces how to use the matplotlib library in Python to draw a particularly beautiful three-group histogram with error bars. Each column has a gradient color, the global font is New Roman, the font is blue, the axis font size is New Roman, and the data is set to be displayed in the center above the column.

First, we need to prepare the data that needs to be plotted. Here we use the numpy module to generate some random data. Here is the sample code:

import numpy as np

# set seed for reproducibility
np.random.seed(12345)

n_groups = 4

# generate data for group 1
means_1 = np.random.randint(50, 100, n_groups)
stds_1 = np.random.randint(1, 5, n_groups)

# generate data for group 2
means_2 = np.random.randint(30, 80, n_groups)
stds_2 = np.random.randint(1, 5, n_groups)

# generate data for group 3
means_3 = np.random.randint(10, 60, n_groups)
stds_3 = np.random.randint(1, 5, n_groups)

首先使用numpy.random.seed()函数设置了随机数生成器的种子,以便于复现结果。然后,我们使用numpy.random.randint()函数生成了每组的4个数据和对应误差棒。


1. Draw charts

Next, you can use the matplotlib library to draw three sets of histograms with error bars.

2. Usage steps

Use the plt.rcParams['font.family'] and plt.rcParams['font.size'] functions to set the global font and font size to New Roman and 16 points. Next, we use the cm.coolwarm, cm.PiYG and cm.YlGn functions to obtain three sets of color gradients respectively, and use the np.linspace() function to divide them into 4 intervals. Then, we saved three sets of colors using the colors1, colors2, and colors3 variables.

Next, set the relevant properties of the histogram, including column width, transparency and error bar parameters. Then, we use the plt.subplots() function to create a Figure object containing the chart and axis objects, and specify the picture size. On the chart, first create the x-axis scale value index of each group, and then use the ax.bar() function to draw the histogram of each group. Each group of column colors adopts a different color gradient scheme, and error bars are set. Finally, labels, titles, and legends were added, and the axis font size was set to font and font size.

Finally, we define the function autolabel() and call it on each of the three sets of bar charts to display the data label at the top center of each bar. This function is implemented by calling the ax.text() function.

1. Import the library

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

2. Complete code

# -*- coding: utf-8 -*-
"""
Created on Sat May 13 13:08:36 2023

@author: ypzhao
"""


import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

# 设置全局字体和字号
font = {
    
    'family': 'Times New Roman', 'size': 18}
plt.rc('font', **font)

# 设置柱状图数据样本 
n_groups = 4
means_1 = (90, 55, 40, 65)
std_1 = (2, 3, 4, 1)

means_2 = (85, 62, 54, 20)
std_2 = (3, 5, 2, 3)

means_3 = (70, 45, 55, 30)
std_3 = (1, 2, 3, 4)

# 准备颜色渐变
cmap = plt.get_cmap('coolwarm')
colors_1 = [cmap(i) for i in np.linspace(0, 1, n_groups)]
cmap = plt.get_cmap('PiYG')
colors_2 = [cmap(i) for i in np.linspace(0, 1, n_groups)]
cmap = plt.get_cmap('YlGn')
colors_3 = [cmap(i) for i in np.linspace(0, 1, n_groups)]


# 绘制柱状图
fig, ax = plt.subplots(figsize=(8, 5),dpi=600)
index = np.arange(n_groups)
bar_width = 0.25

opacity = 0.8
error_config = {
    
    'ecolor': '0.3'}

rects1 = ax.bar(index, means_1, bar_width,capsize=3,
                alpha=opacity, color=colors_1,
                yerr=std_1, error_kw=error_config,
                label='pH1')

rects2 = ax.bar(index + bar_width, means_2, bar_width,capsize=3,
                alpha=opacity, color=colors_2,
                yerr=std_2, error_kw=error_config,
                label='pH2')

rects3 = ax.bar(index + 2*bar_width, means_3, bar_width,capsize=3,
                alpha=opacity, color=colors_3,
                yerr=std_3, error_kw=error_config,
                label='pH3')

# 添加数据标签(显示在柱子上方中央)
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '{:.0f}'.format(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)


# 添加标签、标题和图例
ax.set_xlabel('Group',font)
ax.set_ylabel('Scores',font)
ax.set_title('pH by day and error bar')
ax.set_xticks(index + bar_width)
ax.set_xticklabels(('10', '20', '30', '40'))
ax.legend(loc='best',ncol=3,frameon=False)

# 设置坐标轴字号为新罗马
for tick in ax.xaxis.get_minor_ticks():
    tick.label1.set_fontsize(16)
    tick.label1.set_fontname('Times New Roman')
    
for tick in ax.yaxis.get_minor_ticks():
    tick.label1.set_fontsize(16)
    tick.label1.set_fontname('Times New Roman')

plt.tight_layout()
plt.show()


3. Run and modify

After running the code, three sets of histograms with error bars will be displayed. Each column has a gradient color, the global font is New Roman, the font is blue, the axis font size is New Roman, and the data is displayed in the center above the column.
Insert image description here

Guess you like

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