[Master Python in 100 days] Day64: Python visualization_Matplotlib draws error bar graphs, draws filled graphs, examples + code

1 Draw error bar graph (errorbar)

        Error bar plots are used to visualize measurements of one or more data sets and their associated errors or uncertainties. Each data point may have a different error range, and these errors can be expressed as upper and lower error bars, symmetric errors, asymmetric errors, etc. Typically, error bar plots are used to compare differences between multiple experimental conditions or data sources.

(1) Vertical Error Bars:

  • The upper and lower error bars are used to represent the error range of each data point in the vertical direction. They are usually used to represent the upper and lower floating range of the data point. This can be measurement error, standard deviation, etc.

(2) Symmetric Error:

  • Symmetric error means that the error range of a data point is symmetrical in two directions, and is usually used to express standard deviation or confidence interval, etc.

(3) Asymmetric Error:

  • Asymmetric error means that the error range of a data point is asymmetric in two directions, and is usually used to represent experimental measurement errors, etc.

 Example: Plot an Error Bar Plot

import matplotlib.pyplot as plt
import numpy as np

# 准备数据
x = np.array([1, 2, 3, 4, 5])
y1 = np.array([2, 3, 5, 4, 6])
y2 = np.array([3, 4, 6, 5, 7])

# 不对称误差范围
y1_lower_err = np.array([0.2, 0.3, 0.1, 0.4, 0.15])
y1_upper_err = np.array([0.1, 0.25, 0.15, 0.3, 0.1])

# 对称误差范围
y2_err = np.array([0.15, 0.2, 0.25, 0.2, 0.18])

# 绘制误差线图
plt.errorbar(x, y1, yerr=[y1_lower_err, y1_upper_err], fmt='o', label='Data 1 (Asymmetric Errors)', capsize=5)
plt.errorbar(x, y2, yerr=y2_err, fmt='s', label='Data 2 (Symmetric Errors)', capsize=5)

# 添加标签和标题
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Error Bar Plot')

# 添加图例
plt.legend()

# 显示图形
plt.grid(True)
plt.show()

 run:

         This code is used to draw error bar plots, including asymmetric error ranges and symmetric error ranges. Among them, the x-axis represents the independent variable and the y-axis represents the dependent variable.

        First, prepare the data required for plotting by importing matplotlib.pyplot and the numpy library. The data includes the values ​​of x and the values ​​of the two dependent variables y1 and y2. Next, the upper and lower bound arrays of the asymmetric error range (y1_lower_err and y1_upper_err), and the array of the symmetric error range (y2_err) were created through the numpy library.

        Then, the plt.errorbar function is used to draw the error bars of the two sets of data respectively. The yerr parameter is passed in the array of asymmetric and symmetric error ranges respectively, and the fmt parameter specifies the style of the error bar.

        At the same time, labels and titles are added to explain the meaning of the graph, and legends are added to represent the data involved in the comparison. Finally, call plt.grid(True) to display the grid lines, and call plt.show() to display the graphics.

2 Draw fill diagram (fill_between)

        Fill Between Plot is used to visualize the area between two data sets or the area under a curve. This is often used to express data uncertainty, intervals, or differences between two data sets.

        The key idea of ​​drawing a fill plot is to create a closed shape that encloses the area between the two data sets and fill it. Typically, the two data sets can be two curves, the area between a curve and an axis, or the area between two curves. Fill plots are often used in data visualization to highlight differences or ranges of uncertainty in a data set.

Sample code :

The following is a sample code that demonstrates how to use Matplotlib to draw a filled plot to represent the area between two data sets:

import matplotlib.pyplot as plt
import numpy as np

# 准备数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建填充图
plt.fill_between(x, y1, y2, color='blue', alpha=0.5, label='Region Between y1 and y2')

# 添加标签和标题
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Fill Between Plot')

# 添加图例
plt.legend()

# 显示图形
plt.grid(True)
plt.show()

run:

         In this example, we create two datasets y1and y2and plt.fill_between()plot the filled area between them using the function.

                             Parameter xrepresents the data of x coordinate,

        y1and y2represent the y coordinates of the two data sets respectively,

        colorSpecify the color of the filled area,

        alphaControl the transparency of the filled area,

        labelLabel to use for the legend.

Finally, we added labels, titles, legends, and displayed the filled plot.

This example demonstrates how to draw a fill plot to highlight the area between two data sets and make uncertainty or differences in the data more clearly visible. You can customize the fill pattern's style, color, and properties as needed.

2.2 Draw filled line plot (Filled Line Plot)

  • Filled line graphs are created by coloring the lower area of ​​the line graph. It is used to emphasize trends and changes in data, often indicating the relationship between data points and a baseline.
  • Sample code :
import matplotlib.pyplot as plt
import numpy as np

# 准备数据
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

# 创建填充线图
plt.fill_between(x, y, alpha=0.3)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Filled Line Plot')
plt.show()

In the above example, we used plt.fill_between()the function to create a filled line chart that highlights fluctuations in the data by filling in the area below the line. 

2.3 Stacked Area Plot

  • Stacked area charts are used to represent the cumulative contribution of multiple data series, usually representing the proportions of different categories of data in the population.
  • Sample code :
import matplotlib.pyplot as plt
import numpy as np

# 准备数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建堆叠面积图
plt.stackplot(x, y1, y2, labels=['Sin', 'Cos'], alpha=0.5)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Stacked Area Plot')
plt.legend(loc='upper right')
plt.show()

 run:

        In the example above, we created a stacked area chart using the function , stacking two data series and together, representing their contribution by filling the area.  plt.stackplot()y1y2

2.4 Draw a filled histogram (Filled Histogram)

  • Filling a histogram fills the histogram with color between each bar to emphasize the distribution of different data intervals.
  • Example: Plot a filled histogram comparing male and female height distributions
import matplotlib.pyplot as plt
import numpy as np

# 生成随机数据,模拟身高分布
np.random.seed(0)
male_heights = np.random.normal(175, 10, 500)
female_heights = np.random.normal(162, 8, 500)

# 创建填充直方图,同时显示男性和女性身高分布
plt.hist(male_heights, bins=30, density=True, alpha=0.5, color='blue', label='Male Heights')
plt.hist(female_heights, bins=30, density=True, alpha=0.5, color='pink', label='Female Heights')

# 添加标签和标题
plt.xlabel('Height (cm)')
plt.ylabel('Frequency')
plt.title('Height Distribution (Male vs. Female)')
plt.legend()

# 显示图形
plt.show()

        This code is used to generate random data, simulate the height distribution of men and women, and visualize the height distribution of both by filling the histogram.
        First, prepare the data required for plotting by importing matplotlib.pyplot and the numpy library. The random module in the numpy library was used to generate 500 male height data and female height data that fit the normal distribution.
        Next, the filled histograms of male and female heights were plotted using the plt.hist function. Among them, the bins parameter specifies the number of boxes in the histogram, the density parameter is set to True to convert frequency into probability density, the alpha parameter sets the transparency of the fill color, and the color parameter sets the color of the male height histogram to blue and female respectively
        . The color of the height histogram is pink, and the label parameter specifies the corresponding label.
        Then, labels and titles were added to explain what the graph meant, and a legend was added to indicate the differences between male and female heights.
        Finally, call plt.show() to display the graph. 

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/133002903