Examples of using matplotlib to draw various charts in Python

line chart

A line chart is a chart used to represent trends in data over time, variables, or other continuous changes. By placing time or such a similar continuous variable on the horizontal axis, you can capture how the data changes over time by placing the values ​​of the data points on the vertical axis. Line charts can be used to compare the trends of different variables and easily find differences between different variables.

import matplotlib.pyplot as plt
import numpy as np

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

# 创建一个绘图窗口,大小为8x6英寸
plt.figure(figsize=(8, 6))

# 绘制折线图
plt.plot(x, y1, label='sin(x)')
plt.plot(x, y2, label='cos(x)')

# 添加图例,显示在右上角
plt.legend(loc='upper right')

# 添加标题和轴标签
plt.title('Sin and Cos functions')
plt.xlabel('x')
plt.ylabel('y')

# 显示网格线
plt.grid(True)

# 保存图像,支持多种格式,如PNG、PDF、SVG等
plt.savefig('line_plot.png', dpi=300)

# 显示图像
plt.show()

Example results:

Insert image description here

Parameter Description:

  • plt.figure(figsize=(8, 6)):Creates a drawing window sized 8x6 inches.
  • plt.plot(x, y1, label='sin(x)'): Draw a line chart, x and y1 are the x-coordinates and y-coordinates of the data points, label is the label of the polyline, used for display in the legend.
  • plt.legend(loc='upper right'): Add a legend, the loc parameter specifies the location of the legend, which can be the string 'upper right', etc. or the number 0~10.
  • plt.title('Sin and Cos functions'): Add title.
  • plt.xlabel('x'): Add x-axis labels.
  • plt.ylabel('y'):Add y-axis label.
  • plt.grid(True): Display grid lines.
  • plt.savefig('line_plot.png', dpi=300): Save the image to the file line_plot.png, and the dpi parameter specifies the output resolution.
bar chart

A bar chart is a chart used to compare differences between different sets of data. It displays the differences by expressing the value of each data group as the height of a bar. Histograms can be used to compare the quantity, frequency, or ratio of different categories of data and to show the relative size of that category of data.

import matplotlib.pyplot as plt
import numpy as np

# 生成数据
x = ['A', 'B', 'C', 'D', 'E']
y1 = [3, 7, 2, 5, 9]
y2 = [5, 2, 6, 3, 1]

# 创建一个绘图窗口,大小为8x6英寸
plt.figure(figsize=(8, 6))

# 绘制柱状图
plt.bar(x, y1, color='lightblue', label='Group 1')
plt.bar(x, y2, color='pink', bottom=y1, label='Group 2')

# 添加图例,显示在右上角
plt.legend(loc='upper right')

# 添加标题和轴标签
plt.title('Bar Plot')
plt.xlabel('Category')
plt.ylabel('Value')

# 显示图像
plt.show()

Example results:

bar chart

Parameter Description:

  • plt.bar(x, y1, color='lightblue', label='Group 1'): Draw a histogram, x is a list of categories, y1 is the value corresponding to each category, label is the label of the data set, used for display in the legend. The color parameter specifies the color of the histogram.
  • plt.bar(x, y2, color='pink', bottom=y1, label='Group 2'): Draw a histogram of the second set of data. The bottom parameter specifies the bottom position of the set of data.
  • plt.legend(loc='upper right'): Add a legend, the loc parameter specifies the location of the legend, which can be the string 'upper right', etc. or the number 0~10.
  • plt.title('Bar Plot'): Add title.
  • plt.xlabel('Category'): Add x-axis labels.
  • plt.ylabel('Value'):Add y-axis label.
Histogram

Histograms are used to display the distribution of data and are often used to analyze characteristics such as skewness and kurtosis of data sets.

import matplotlib.pyplot as plt
import numpy as np

# 生成随机数据
np.random.seed(42)
data = np.random.normal(size=1000)

# 绘制直方图
fig, ax = plt.subplots()
ax.hist(data, bins=30, density=True, alpha=0.5, color='blue')

# 设置图表标题和坐标轴标签
ax.set_title('Histogram of Random Data', fontsize=16)
ax.set_xlabel('Value', fontsize=14)
ax.set_ylabel('Frequency', fontsize=14)

# 设置坐标轴刻度标签大小
ax.tick_params(axis='both', which='major', labelsize=12)

# 显示图表
plt.show()

Example results:
Insert image description here

Parameter Description:

  • data: The data set to plot.
  • bins: Number of bins in the histogram.
  • density: whether to convert frequencies into probability density.
  • alpha: The transparency of the histogram.
  • color: The color of the histogram.
  • ax.set_title(): Set the chart title.
  • ax.set_xlabel(): Set the x-axis label.
  • ax.set_ylabel(): Set the y-axis label.
  • ax.tick_params(): Set the size of the axis tick labels.
pie chart

Pie charts are used to display the proportion of data, usually to compare the proportions between different categories or parts.

import matplotlib.pyplot as plt

# 生成数据
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
colors = ['red', 'green', 'blue', 'yellow']

# 绘制饼图
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)

# 设置图表标题
ax.set_title('Pie Chart of Data', fontsize=16)

# 显示图表
plt.show()

Example results:
Insert image description here

Parameter Description:

  • labels: category labels of the data.
  • sizes: proportion of data.
  • colors: The color of the data.
  • autopct: The display format of the proportion.
  • startangle: the starting angle of the pie chart.
  • ax.set_title(): Set the chart title.
bracket diagram

A bracket chart is a chart used to compare the distribution of different sets of data. It is used to display the median, upper and lower quartiles, minimum and maximum values ​​of the data, which can help us understand the shape, location and degree of dispersion of the data distribution. In the bracketed plot, each box represents the 25% to 75% quantile of the data, the median line is the median within each box, and the ordinary line is the minimum and maximum values ​​outside each box.

import matplotlib.pyplot as plt

# 生成数据
data = [[3.4, 4.1, 3.8, 2.0], [2.3, 4.5, 1.2, 4.3]]

# 创建一个绘图窗口,大小为8x6英寸
plt.figure(figsize=(8, 6))

# 绘制括线图
bp = plt.boxplot(data, widths=0.5, patch_artist=True, notch=True)

# 设置每个箱线图的颜色和填充
for patch, color in zip(bp['boxes'], ['lightblue', 'pink']):
    patch.set_facecolor(color)

# 添加标题和轴标签
plt.title('Box Plot')
plt.xlabel('Group')
plt.ylabel('Data')

# 显示图像
plt.show()

Example results:

Insert image description here

Parameter Description:

  • plt.boxplot(data, widths=0.5, patch_artist=True, notch=True): Draw a bracket chart, data is a list containing two lists, representing two sets of data. The widths parameter specifies the width of each boxplot, the patch_artist parameter specifies the use of patches to fill the boxplot, and the notch parameter specifies the scoreboard in the boxplot.
  • patch.set_facecolor(color): Set the color and filling of each box plot. The zip function can pack the two lists into a tuple and take out the values ​​of the tuples one by one.
  • plt.title('Box Plot'): Add title.
  • plt.xlabel('Group'): Add x-axis labels.
  • plt.ylabel('Data'):Add y-axis label.
Scatter plot

A scatter plot is a graph used to show the relationship between two variables. Each point represents a data point, and its position is determined by the value of the variable. Scatter plots can be used to find correlations between variables and display any outliers or outliers in the data.

import matplotlib.pyplot as plt
import numpy as np

# 生成数据
x = np.random.normal(size=100)
y = np.random.normal(size=100)

# 创建一个绘图窗口,大小为8x6英寸
plt.figure(figsize=(8, 6))

# 绘制散点图
plt.scatter(x, y, s=50, alpha=0.5)

# 添加标题和轴标签
plt.title('Scatter Plot')
plt.xlabel('x')
plt.ylabel('y')

# 显示图像
plt.show()

Example results:

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-GM4O5nQt-1686898200230) (null)]

Parameter Description:

  • plt.scatter(x, y, s=50, alpha=0.5): Draw a scatter plot, x and y are the x and y coordinates of the data points, s specifies the size of the point, and alpha specifies the transparency of the point.
  • plt.title('Scatter Plot'): Add title.
  • plt.xlabel('x'): Add x-axis labels.
  • plt.ylabel('y'):Add y-axis label.
boxplot

Box plots are used to display information such as the distribution of data and outliers, and are usually used to compare differences between different data sets.

import matplotlib.pyplot as plt
import numpy as np

# 生成随机数据
np.random.seed(42)
data = np.random.normal(size=(100, 4), loc=0, scale=1.5)

# 绘制箱线图
fig, ax = plt.subplots()
ax.boxplot(data, notch=True, sym='o', vert=True, whis=1.5)

# 设置图表标题和坐标轴标签
ax.set_title('Boxplot of Random Data', fontsize=16)
ax.set_xlabel('Variable', fontsize=14)
ax.set_ylabel('Value', fontsize=14)

# 设置坐标轴刻度标签大小
ax.tick_params(axis='both', which='major', labelsize=12)

# 显示图表
plt.show()

Example results:
Insert image description here

Parameter Description:

  • data: The data set to plot.
  • notch: whether to draw a notch.
  • sym: Marker shape for outliers.
  • vert: Whether to draw box plots vertically.
  • whis: The whisker length of the box plot, based on 1.5 times the interquartile range.
  • ax.set_title(): Set the chart title.
  • ax.set_xlabel(): Set the x-axis label.
  • ax.set_ylabel(): Set the y-axis label.
  • ax.tick_params(): Set the size of the axis tick labels.
heat map

Heat maps are used to display relationships and trends between data, and are usually used to analyze correlations and changes in two-dimensional data.

import matplotlib.pyplot as plt
import numpy as np

# 生成随机数据
np.random.seed(42)
data = np.random.normal(size=(10, 10), loc=0, scale=1)

# 绘制热力图
fig, ax = plt.subplots()
im = ax.imshow(data, cmap='YlOrRd')

# 添加颜色条
cbar = ax.figure.colorbar(im, ax=ax)
cbar.ax.set_ylabel('Values', rotation=-90, va='bottom')

# 添加轴标签和标题
ax.set_xticks(np.arange(len(data)))
ax.set_yticks(np.arange(len(data)))
ax.set_xticklabels(np.arange(1, len(data)+1))
ax.set_yticklabels(np.arange(1, len(data)+1))
ax.set_title('Heatmap of Random Data', fontsize=16)

# 显示图表
plt.show()

Example results:
Insert image description here

Parameter Description:

  • data: The data set to plot.
  • cmap: Color map, used to represent the color range of data size.
  • ax.imshow(): Draw heat map.
  • cbar.ax.set_ylabel(): Set the label of the color bar.
  • ax.set_xticks(): Set x-axis tick labels.
  • ax.set_yticks(): Set the y-axis tick labels.
  • ax.set_xticklabels(): Set the label name of the x-axis tick label.
  • ax.set_yticklabels(): Set the label name of the y-axis tick label.
  • ax.set_title(): Set the chart title.
Tree

Tree diagrams are used to display the hierarchical structure and relationships between data, and are usually used to analyze issues such as tree structures and organizational structures.

import matplotlib.pyplot as plt

# 绘制树状图
fig, ax = plt.subplots()

ax.barh('CEO', 1, color='black')
ax.barh('VP1', 0.8, left=1, color='gray')
ax.barh('VP2', 0.8, left=1, color='gray')
ax.barh('Manager1', 0.6, left=1.8, color='gray')
ax.barh('Manager2', 0.6, left=1.8, color='gray')
ax.barh('Manager3', 0.6, left=1.8, color='gray')
ax.barh('Supervisor1', 0.4, left=2.4, color='gray')
ax.barh('Supervisor2', 0.4, left=2.4, color='gray')
ax.barh('Supervisor3', 0.4, left=2.4, color='gray')
ax.barh('Staff1', 0.2, left=3.2, color='gray')
ax.barh('Staff2', 0.2, left=3.2, color='gray')
ax.barh('Staff3', 0.2, left=3.2, color='gray')
ax.barh('Staff4', 0.2, left=3.2, color='gray')

# 设置轴标签和标题
ax.set_yticks([])
ax.set_xlim(0, 4)
ax.set_xlabel('Hierarchy', fontsize=14)
ax.set_title('Tree Diagram of Organization', fontsize=16)

# 显示图表
plt.show()

Example results:
Insert image description here

Parameter Description:

  • ax.barh(): Draws a horizontal bar chart.
  • ax.set_yticks(): Set the y-axis tick labels.
  • ax.set_xlim(): Set the x-axis coordinate range.
  • ax.set_xlabel(): Set the x-axis label.
  • ax.set_title(): Set the chart title.

Guess you like

Origin blog.csdn.net/u012534326/article/details/131246811