Python randomly generates data and plots two line charts with error bars using dual y-axes

python drawing series article directory

往期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 a histogram and beautifies it | Filling the columns with different colors
Python draws a histogram with error bars Gradient color filling with data annotation (advanced)



Preface

In data visualization, sometimes it is necessary to perform statistical tests on the data, such as calculating the mean, standard deviation, confidence interval, etc. In order to understand the distribution of data more intuitively, we usually use a line graph with error bars to display the data.

In Python, matplotlib is a very powerful drawing library that supports many different types of charts and can achieve high-quality data visualization through simple code. This article will introduce how to use matplotlib to draw a line graph with error bars, and provide sample code for demonstration.


1. Preparation work

1.1 Environment setup

Before starting, you need to make sure you have the matplotlib library installed. If you haven't installed it yet, you can install it using the following command:

pip install matplotlib

Of course, in addition to the matplotlib library, we also need to use the numpy library to generate random numbers in order to demonstrate the sample code. Likewise, if you have not installed the numpy library, you can install it using the following command:

pip install numpy

2. Draw a line graph with error bars

First, let's take a look at the matplotlib function needed to draw a line graph with error bars: ax.errorbar(). This function adds error bars to an existing chart to show the range of data.
Here is the syntax of ax.errorbar():

ax.errorbar(x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None, 
capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, 
xuplims=False, errorevery=1, capthick=None, *, data=None, **kwargs)

Among them, the parameters x and y represent the x coordinate and y coordinate of the data respectively; the parameters yerr and xerr represent the error bar sizes in the y direction and x direction respectively; the parameter fmt can set the line type, color, mark symbol and other attributes of the error bar; parameters capsize sets the length of the bar at the end of the error bar.

Here, we take drawing two line graphs with error bars as an example to look at the specific implementation method.

  1. First, we need to import the matplotlib and numpy libraries and create two subplots ax1 and ax2.
  2. Then, we use the numpy library to generate two sets of random data.
  3. Finally, we plot two polylines separately and add error bars using the ax.errorbar() function.

1. Import the library

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

2. Data generation

In the above code, I used the Numpy library to generate two sets of random data sets containing 10 data points. Among them, y1 corresponds to the left y-axis, and y2 corresponds to the right y-axis.

# 生成随机数据
x = np.arange(0, 10, 1)
y1 = np.random.normal(5, 2, len(x))
y2 = np.random.normal(10, 3, len(x))

err1 = np.random.normal(1, 0.5, len(x)) This line of code is used to generate error bar data, where np.random.normal() is a method in the NumPy library, used to generate normal Distributed random numbers.

Specifically, this method accepts three parameters, namely mean loc, standard deviation scale, and the number of generated random numbers size. The return value of this method is an array containing the specified number of random numbers.

In this line of code, I use a normal distribution with mean 1 and standard deviation 0.5 to generate 10 random numbers of the same length as the data set y1. These random numbers are then used as the "radius" (i.e. the error value) of the error bars in order to plot the error bars on the line chart.

ax1.errorbar(x, y1, yerr=err1, fmt='o', color='#6D8F18', markersize=8,capsize=5)
ax2.errorbar(x, y2, yerr=err2, fmt='*', color='#3F7F4C', markersize=8,capsize=5)

capsize sets the width of the error bar.
Next, I use the errorbar() method to draw the error bar, and use the twinx() method to create the second coordinate axis. The parameters of the ax.grid() method are changed to visible=False, so that the grid can be The line is set to invisible.
Then, I set the axis labels and titles and used the double legend() method to correspond to the two lines.

Finally, I set the axis font and size, and used the spines attribute and the tick_params() method to set the colors of the two axes to be inconsistent.

3. Complete code

# -*- coding: utf-8 -*-
"""
Created on Mon May 15 22:59:50 2023

@author: ypzhao
"""

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

# 设置字体和字号
matplotlib.rcParams['font.family'] = 'Times New Roman'
matplotlib.rcParams['font.size'] = 24

font = {
    
    'family':'Times New Roman','size':28}
# 创建画布和子图
fig, ax1 = plt.subplots(figsize=(10,6),dpi=300)
ax2 = ax1.twinx()

# 生成随机数据
x = np.arange(0, 10, 1)
y1 = np.random.normal(5, 2, len(x))
y2 = np.random.normal(10, 3, len(x))

# 绘制折线图
ax1.plot(x, y1, color='#6D8F18', label='Line 1')
ax2.plot(x, y2, color='#3F7F4C', label='Line 2')

# 添加误差棒
err1 = np.random.normal(1, 0.5, len(x))
err2 = np.random.normal(1.5, 0.8, len(x))

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


ax1.errorbar(x, y1, yerr=err1, fmt='o', color='#6D8F18', markersize=8,capsize=5)
ax2.errorbar(x, y2, yerr=err2, fmt='*', color='#3F7F4C', markersize=8,capsize=5)

# 设置坐标轴标签和标题
ax1.set_xlabel('day')
ax1.set_ylabel('pH1', color='#6D8F18')
ax2.set_ylabel('pH2', color='#3F7F4C')
ax1.set_title('Two Lines with Errorbars',font)

# 设置legend的显示样式和字体
ax1.legend(loc=1, prop={
    
    'family': 'Times New Roman', 'size': 16})
ax2.legend(loc=2, prop={
    
    'family': 'Times New Roman', 'size': 16})

# 设置坐标轴字体和字号
for ax in [ax1, ax2]:
    ax.tick_params(axis='both', which='major', labelsize=20)
    for tick in ax.get_xticklabels() + ax.get_yticklabels():
        tick.set_fontname('Times New Roman')

# 设置网格线不可见
ax1.grid(visible=False)
ax2.grid(visible=False)

# 设置双坐标轴的颜色不一致
ax1.spines['left'].set_color('#6D8F18')
ax1.spines['right'].set_color('#3F7F4C')
ax1.tick_params(axis='y', colors='#6D8F18')
ax2.tick_params(axis='y', colors='#3F7F4C')

plt.show()

Call the ax1.plot() and ax2.plot() functions respectively to draw two polylines, and use the ax1.errorbar() and ax2.errorbar() functions to add error bars. Among them, we set fmt='o' to indicate that the end of the error bar uses a circular mark symbol, color='#6D8F18' indicates that the color of the error bar is green, and capsize=5 indicates that the length of the horizontal bar at the end of the error bar is 5.

When using matplotlib to draw a line graph with error bars, you only need to use the ax.errorbar() function to add error bars. During the specific implementation, you can set the line type, color, mark symbol, end bar length and other attributes of the error bar as needed to better display the variation range of the data.

4. Operation results

Insert image description here

Guess you like

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