Python data visualization - matplotlib learning summary

Table of contents

(1) Common graphics

1. Trend graph (line graph): plot()

2. Scatter plot: scatter():

(2) Statistical graphics

1. Histogram: bar(

2. Bar graph: barh()

3. Histogram: hist()

4. Pie chart: pie()

5. Level line diagram: polar()

6. Bubble chart (scatter plot): scatter()

7. Dendrogram (Cotton Swab Diagram): stem()

8. Box plot: boxplot()

9. Error bar graph: errorbar()

 (3) Graphic style

1. Set the scale style

2. Add instruction annotations and non-instruction annotations

3. The projection effect of title and axis

4. Transfer axis

5. Divide the window: subplot()

(1) Common graphics

1. Trend graph (line graph): plot()

import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)  # 生成0~10之间的100个数
y = np.sin(x)  # 计算纵坐标
plt.plot(x, y)  # 绘制折线图
plt.title('Sin函数图像')  # 添加标题
plt.xlabel('x轴')  # 添加x轴标签
plt.ylabel('y轴')  # 添加y轴标签
#plt.xlim(-2,2)     #设定 x 坐标轴的显示范围在[-2,2]
#plt.axhline(y=0)    #添加水平参考线
#plt.grid()  #绘制网格线
#plt.axhline(y=0)    #绘制y=0的刻度线
#plt.axvspan(-4,2,facecolor='gray', alpha=0.3)    #添加在-4到2的垂直方向的颜色区域,填充颜色为灰色,透明度为 0.3

plt.show()  # 显示图形

pyplot arguments:

  • x: x-axis data, usually an array or list.

  • y: y-axis data, usually an array or list.

  • label: Label, used to explain the name or meaning of the data. xlabel用于x轴,ylabel用于y轴

  • color或c: Color, the default is blue, and it can also be an RGB value or a color name.

  • marker: Point markers to show the shape of each data point.

  • linestyle或ls: Line type, used to control the style, thickness, etc. of the line.

  • linewidth或lw: Line width, used to control the width of the line.

  • alpha: Transparency, used to control the transparency of line or point markers.

  • xlimand ylim: the range of the x-axis and y-axis, used to set the scale range of the coordinate axis.

  • title: Title, used to add a title to the entire graph.

  • grid: Draw tick grid lines

  • axhline: Draw a horizontal parameter line parallel to the x-axis

  • axvspan: Draw a horizontal parametric area perpendicular to the x-axis

  • annotate: Add point-to-point annotations for graphic content details

  • text: A non-pointing comment that adds details of the graphic content

  • legend: used to add a custom legend to the image

 result:

 

2. Scatter plot: scatter():

import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

# 设置数据
x = np.random.rand(50)
y = np.random.rand(50)
# 绘制散点图
plt.scatter(x, y, s=50, c='b', marker='o', alpha=0.5)
# 添加标题和坐标轴标签
plt.title('散点图')
plt.xlabel('x轴')
plt.ylabel('y轴')
# 显示图像
plt.show()

Parameter explanation:

  • x : the data of the x-axis of the scatter plot;
  • y : the data of the y-axis of the scatter plot;
  • s : The size of the scatter point, that is, the size of the marker;
  • c : the color of the scatter point;
  • marker : The shape of the scatter point, the default is circle;
  • alpha : Transparency, the value range is 0~1, the smaller the value, the higher the transparency.

 result:

 

(2) Statistical graphics

1. Histogram: bar(

bar(x, height, width=0.8, bottom=None, align='center', data=None, **kwargs)
  • x: the x-coordinate data of the histogram;
  • height: The height of the column chart, corresponding to the height of each x-coordinate data;
  • width: Column width, the default is 0.8;
  • bottom: The bottom position of the column, the default is None, which means that the bottom is set as the y-axis of the drawing plane;
  • align: The alignment of the column, which can be  'center', 'edge' etc.;
  • data: Data source object, which can be a variety of data types, such as DataFrame, Series, array, etc.;
  • kwargs: Other optional parameters, including column color, border color, label position and other related settings.
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

# 生成数据
x = ['A', 'B', 'C', 'D', 'E']
y = np.random.randint(0, 10, size=(len(x)))

# 绘制柱状图
plt.bar(x, y, width=0.6, bottom=None, align='center', alpha=0.8)

# 添加标签
for i, v in enumerate(y):
    plt.text(i, v+0.2, str(v), ha='center', fontsize=10)
# 显示图形
plt.show()

 

2. Bar graph: barh()

barh(y, width, height=0.8, left=None, align='center', data=None, **kwargs)
  • y: the y coordinate data of the bar;
  • width: The width of the column bar, corresponding to the width of each y coordinate data;
  • height: The height of the bar, the default is 0.8;
  • left: The left position of the column, the default is None, which means that the left side is set as the x-axis of the drawing plane;
  • align: The alignment of the column, which can be  'center', 'edge' etc.;
  • data: Data source object, which can be a variety of data types, such as DataFrame, Series, array, etc.;
  • kwargs: Other optional parameters, including column color, border color, label position and other related settings.
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

# 生成数据
y = ['A', 'B', 'C', 'D', 'E']
x = np.random.randint(0, 10, size=(len(y)))

# 绘制水平柱状图
plt.barh(y, x, height=0.6, left=None, align='center', alpha=0.8)

# 添加标签
for i, v in enumerate(x):
    plt.text(v+0.2, i, str(v), va='center', fontsize=10)

# 显示图形
plt.show()

 

3. Histogram: hist()

hist(x, bins=None, range=None, density=False, 
    weights=None, cumulative=False, bottom=None,
    histtype='bar', align='mid', orientation='vertical',
    rwidth=None, log=False, color=None, label=None, stacked=False, 
    normed=None, **kwargs)

  • x: The data that needs to draw the histogram;
  • bins: Used to specify the width of each bin, which can be a single integer, sequence or string. The default is 10, which means that the data range is divided into 10 equal parts;
  • range: The data range that needs to draw the histogram;
  • density: Whether to normalize the histogram, its value is False by default;
  • weights: The weight array used to form the histogram;
  • cumulative: Whether to draw a cumulative frequency graph, the default is False;
  • bottom: the height of the bottom of the stacked graph;
  • histtype: Specify the histogram type, which can be  'bar', 'barstacked', 'step', 'stepfilled' etc.;
  • align: the alignment of the histogram;
  • orientation: The drawing method of the histogram, which can be  'horizontal' or  'vertical';
  • rwidth: The relative width of the histogram, when the value is 1, there is no gap, and when the value is 0.5, the spacing is equal to half the width of the histogram;
  • log: Whether to perform logarithmic transformation on the y-axis;
  • color: the color of the histogram;
  • label: the label of the histogram;
  • stacked: Whether to draw the histogram in a stacked manner, the default is False;
  • normed: has been deprecated and can be  density replaced by parameters;
  • kwargs: Other optional parameters, including histogram border, fill, color and other related settings.
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(2022)
data = np.random.randn(10000)

# 绘制直方图
plt.hist(data, bins=40, range=(-4, 4), density=False, alpha=0.8, color='blue')
plt.xlabel('x')
plt.ylabel('频率')
plt.title('直方图')

# bins 设为 40,表示将数据范围等分成 40 份;
# range 设为 (-4, 4),表示数据范围在[-4,4]之间
# density 设为 False,表示不需要将直方图归一化;
# alpha 设为 0.8,表示直方图颜色透明度为 0.8;
# color 设为 'blue',表示直方图颜色为蓝色;

# 显示图像
plt.show()

 

4. Pie chart: pie()

pie(x, explode=None, labels=None, colors=None, 
    autopct=None, pctdistance=0.6, shadow=False, 
    labeldistance=1.1, startangle=None, radius=None, counterclock=True, 
    wedgeprops=None, textprops=None, center=(0, 0), frame=False, 
    rotatelabels=False, **kwargs)
  • x: The data used to draw the pie chart, which can be iterable objects such as arrays, lists, and tuples;
  • explode: Used to specify the offset between each pie chart;
  • labels: Used to specify the label corresponding to each pie chart;
  • colors: Used to specify the color corresponding to each pie chart;
  • autopct: A format string used to specify the proportion of each pie chart;
  • pctdistance: Used to specify the distance between the percentage label and the center of the circle;
  • shadow: Do you need to add a shadow effect, the default is False;
  • labeldistance: Specify the multiple of the distance between each pie chart label and the center of the circle;
  • startangle: Specify the angle at which the pie chart starts to be drawn, the default is 0;
  • radius: Specify the radius of the pie chart;
  • counterclock: Specifies the direction in which the pie chart is drawn, the default is True, that is, it is drawn counterclockwise;
  • wedgeprops: Used to specify the properties of the pie chart ring, such as linewidth, edgecolor, etc.;
  • textprops: It is used to specify the attributes of the proportion label, such as fontsize, color, etc.;
  • center: Specify the coordinates of the center position of the pie chart;
  • frame: Do you need to draw a border, the default is False;
  • rotatelabels: Whether to rotate the pie chart label, the default is False;
  • kwargs: Other optional parameters, including drawing style, font, font size and other related settings.

import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(2022)
data = np.random.randn(10000)

import matplotlib.pyplot as plt

# 生成数据
labels = ['A', 'B', 'C', 'D', 'E']
sizes = [15, 30, 45, 10, 5]
colors = ['red', 'blue', 'green', 'orange', 'gray']
explode = [0.1, 0, 0, 0, 0]

# 绘制饼图
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)

plt.axis('equal')
plt.show()

 

5. Level line diagram: polar()

polar(theta, r, **kwargs)
  • theta: The angle data used to draw the polar coordinate diagram, the unit is radian;
  • r: The size data used to draw the polar coordinate diagram, which represents a set of size data corresponding to the angle,  theta corresponding to ;
  • kwargs: Other optional parameters, including polar coordinate filling, color and other related settings.
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

# 生成一些随机数据
theta = np.linspace(0, 2*np.pi, 1000)
r = np.random.rand(1000)

# 绘制极坐标图
plt.polar(theta, r)
plt.show()

 

6. Bubble chart (scatter plot): scatter()

scatter(x, y, s=None, c=None, marker=None, cmap=None, 
norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, 
edgecolors=None, plotnonfinite=False, data=None, **kwargs)
  • x: the x-coordinate of the scatter plot;
  • y: the y coordinate of the scatter plot;
  • s: The size (area) of the scatter point, which can be a constant, an array, a list or a tuple;
  • c: The color of the scatter point, which can be a constant, an array, a list or a tuple;
  • marker: Scatter mark symbol;
  • cmap: colormap used to specify the color of the scatter point;
  • norm: used to specify the normalization method of the colormap;
  • vmin: Used to specify the minimum value of the colormap;
  • vmax: used to specify the maximum value of the colormap;
  • alpha: Transparency of scattered points;
  • linewidths: Used to specify the edge line width of scattered points;
  • edgecolors: It is used to specify the color of the edge line of the scatter point, and the default is  'face', indicating that the color of the scatter point is used;
  • plotnonfinite: Whether to draw non-finite values, the default is False;
  • data: Data source object, which can be a variety of data types, such as DataFrame, Series, array, etc.;
  • kwargs: Other optional parameters, including scatter color, edge color, label position and other related settings
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

# 生成数据
np.random.seed(2022)
x = np.random.randn(50)
y = np.random.randn(50)
colors = np.random.randint(0, 10, 50)

# 绘制散点图
plt.scatter(x, y, s=20*abs(x+y)+100, c=colors, cmap='viridis', alpha=0.8)

# 添加红色边缘线
plt.scatter(x, y, s=20*abs(x+y)+100, facecolors='none', edgecolors='red', linewidths=1)

# 添加标题和坐标轴标签
plt.title('气泡图')
plt.xlabel('X')
plt.ylabel('Y')

# 显示图像
plt.show()

 

7. Dendrogram (Cotton Swab Diagram): stem()

stem(x, y, linefmt=None, markerfmt=None, basefmt=None, bottom=None, 
    label=None, use_line_collection=None, data=None, **kwargs)
  • x: the x-coordinate of the dendrogram;
  • y: the y coordinate of the dendrogram;
  • linefmt: format string used to specify the line segment of the dendrogram;
  • markerfmt: A format string used to specify dendrogram markers;
  • basefmt: format string used to specify the baseline of the dendrogram;
  • bottom: Baseline height when drawing a dendrogram with a stacked style;
  • label: label of dendrogram;
  • use_line_collection: Whether to use  LineCollection to draw line segments, the default is True;
  • data: Data source object, which can be a variety of data types, such as DataFrame, Series, array, etc.;
  • kwargs: Other optional parameters, including line style, marker style, label position and other related settings.
# 生成数据
np.random.seed(2022)
x = np.linspace(0.0, 2.0*np.pi, 100)
y = np.sin(x)

x = np.arange(0, 10, 1)
y = np.random.rand(10)

# 绘制离散波形图
plt.stem(x, y)
plt.show()

8. Box plot: boxplot()

boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, 
    widths=None, patch_artist=None, bootstrap=None, usermedians=None, 
    conf_intervals=None, meanline=None, showmeans=None, showcaps=None, 
    showbox=None, showfliers=None, boxprops=None, labels=None, 
    flierprops=None, medianprops=None, meanprops=None, capprops=None, 
    whiskerprops=None, manage_xticks=True, autorange=False, zorder=None, 
    data=None)
  • x: The data of the boxplot, which can be an array, list, DataFrame, etc.;
  • notch: Whether to draw a gap, the default  Falseis to draw a box plot instead of a half crescent tooth plot;
  • sym: The marker symbol used to specify outliers, the default is  None;
  • vert: Whether to draw a vertical boxplot, the default is  True;
  • whis: Used to specify the length of the upper and lower positions (whiskers) of the boxplot, the default is  1.5;
  • positions: Used to specify the position of the boxplot, the default is  [1, 2, ..., n], where  n is the number of data columns;
  • widths: Used to specify the width of the boxplot;
  • patch_artist: Whether to allow to fill the boxplot, mainly used for custom colors and styles, the default is  False;
  • bootstrap: Used to specify the number of samples for calculating the confidence interval;
  • usermedians: Manually specify the median value;
  • conf_intervals: Used to specify the method and confidence level for calculating the confidence interval, the default is  None;
  • meanline: Whether to draw the mean line, the default is  False;
  • showmeans: Whether to display the mean value, the default is  False, it is usually not recommended to display;
  • showcaps: Whether to display the line segment at the end of the boxplot  whisker , the default is  True;
  • showbox: Whether to display the boxplot frame, the default is  True;
  • showfliers: Whether to display outliers, the default is  True;
  • boxprops: Used to specify the properties of the boxplot frame, such as linewidth, edgecolor, etc.;
  • labels: Used to specify the label of the boxplot;
  • flierprops: used to specify the attributes of outliers, such as markersize, markerfacecolor, etc.;
  • medianprops: used to specify the attributes of the median line, such as linewidth, color, etc.;
  • meanprops: Used to specify the attributes of the mean line, such as linewidth, linestyle, color, etc.;
  • cappropswhisker : It is used to specify the attributes of the hat at the end of the boxplot line  segment, such as linewidth, linestyle, color, etc.;
  • whiskerprops: Used to specify the properties of the line segment of the boxplot  whisker , such as linewidth, linestyle, color, etc.;
  • manage_xticks: Whether to automatically manage the x-axis scale, the default is  True;
  • autorange: Whether to automatically adjust the coordinate axis range, the default is  False;
  • zorder: It is used to specify the layer order, usually no setting is required;
  • data: Data source object, which can be a variety of data types, such as DataFrame, Series, array, etc.
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

# 生成一些随机数据
data = np.random.randn(100, 5)

# 绘制箱线图
plt.boxplot(data)
plt.show()

 

 

9. Error bar graph: errorbar()

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, label='', **kwargs)
  • x: the x-coordinate of the error bar graph;
  • y: the y coordinate of the error bar graph;
  • yerr: The length of the vertical line segment used to specify the error range, which can be a number, scalar or array;
  • xerr: The length of the horizontal line segment used to specify the error range, which can be a number, scalar or array;
  • fmt: format used to specify the color, line type and marker symbol of the point;
  • ecolor: Used to specify the color of error bars and hats;
  • elinewidth: Used to specify the line width of the error line segment;
  • capsize: Used to specify the size of the error hat;
  • barsabove: Whether to draw the error bars on the data points;
  • lolims: Whether to draw the lower limit error smaller than the data point;
  • uplims: Whether to draw the upper limit error greater than the data point;
  • xlolims: Whether to draw the horizontal lower limit error smaller than the data point;
  • xuplims: Whether to draw the horizontal upper limit error greater than the data point;
  • errorevery: Sampling interval for specifying error entries;
  • capthick: used to specify the line width of the error hat;
  • label: label name;
  • kwargs: Other optional parameters, including related settings such as where the error hat stops.
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

#生成数据
x = np.arange(0, 10, 1)
y = np.random.rand(10)
yerr = np.random.rand(10) * 0.2

# 绘制带误差线的散点图
plt.errorbar(x, y, yerr=yerr, fmt='o')
plt.show()

 (3) Graphic style

1. Set the scale style

Setting the scale style requires two methods: xticks and yticks:

xticks(ticks=None, labels=None, **kwargs)
yticks(ticks=None, labels=None, **kwargs)
  • ticks: A sequence or array used to set the tick position;
  • labels: A sequence or array for setting tick labels;
  • kwargs: Other optional parameters, such as font, font size, rotation angle, etc.

Common scene

Set the tick label font size

import matplotlib.pyplot as plt

# 创建图形,并设置 x 轴、y 轴刻度标签字体大小为 14
fig, ax = plt.subplots()
ax.tick_params(axis='both', labelsize=14)

 Set tick interval and range

import numpy as np
import matplotlib.pyplot as plt

# 创建图形并绘制曲线
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)

# 设置 x 轴刻度范围为 0 到 10,刻度间隔为 2
ax.set_xticks(np.arange(0, 11, 2))

Custom tick labels

import numpy as np
import matplotlib.pyplot as plt

# 创建图形并绘制曲线
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)

# 自定义 y 轴刻度标签
ax.set_yticks([-1, 0, 1])
ax.set_yticklabels(['Low', 'Medium', 'High'])

hide scale

import numpy as np
import matplotlib.pyplot as plt

# 创建图形并绘制曲线
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)

# 隐藏 y 轴刻度
ax.tick_params(axis='y', which='both', length=0)

2. Add instruction annotations and non-instruction annotations

Add instruction annotation:

annotate(text, xy, xytext=None, arrowprops=None, **kwargs)
  • text: Annotation text content;
  • xy: Annotate target coordinates, indicating the location of the arrow;
  • xytext: the position of the annotation text, if not specified, it will be  xy the parameter by default;
  • arrowprops: The property of the arrow, you can specify the length, width, color, etc. of the arrow;
  • kwargs: Other optional parameters, including text color, font, font size, etc.

import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

# 生成数据
x = np.linspace(0, 1, 100)
y = np.sin(x*10)

# 绘制 sin(x) 的图像
plt.plot(x, y)

# 添加注释:最大值处对应的 x 坐标和 y 坐标
max_y = np.max(y)
max_idx = np.argmax(y)
plt.annotate(f'Max={max_y:.2f}', xy=(x[max_idx], max_y),
             xytext=(x[max_idx]-0.2, max_y+0.3),
             arrowprops=dict(arrowstyle='->', lw=2))

# 显示图形
plt.show()

 

Add a non-directive annotation

text(x, y, s, fontdict=None, withdash=False, **kwargs)
  • x And  y: the position of the text box, which can be image coordinates, data coordinates or coordinate axis score coordinates, etc.;
  • s: Text label content;
  • fontdict: Font attribute parameter, supports font, font size, color and other related settings;
  • withdash: Text border attribute, you can set whether to use a dotted border;
  • kwargs: Other optional parameters, including aspect ratio, text arrangement, rotation angle, alignment and other related settings.
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

# 生成数据
x = np.linspace(-5, 5, 100)
y = np.sin(x)

# 绘制 sin(x) 的图像
plt.plot(x, y)

# 添加文本标签:最大值处对应的 x 坐标和 y 坐标
max_y = np.max(y)
max_idx = np.argmax(y)
plt.text(x[max_idx], max_y, f'Max={max_y:.2f}', fontsize=12,
         color='red', ha='center', va='bottom')

# 显示图形
plt.show()

3. The projection effect of title and axis

To set the projection effect, you need to use set_path_effects()

import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patheffects as pe

x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)

ax.plot(x, y)
ax.set_title('sin(x)')

# 设置标题阴影效果
title_text_obj = ax.set_title('Title', fontsize=18, fontweight='bold')
title_text_obj.set_path_effects([pe.withStroke(linewidth=2, foreground='gray')])

# 设置坐标轴标签阴影效果
x_label_obj = ax.set_xlabel('X Label', fontsize=16)
y_label_obj = ax.set_ylabel('Y Label', fontsize=16)
x_label_obj.set_path_effects([pe.withStroke(linewidth=1, foreground='gray')])
y_label_obj.set_path_effects([pe.withStroke(linewidth=1, foreground='gray')])

plt.show()

4. Transfer axis

To transfer the coordinate axis, you need to use the set_zorder method

import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()

ax.plot(x, y)
ax.set_title('sin(x)')

# 将 x 轴和 y 轴的刻度放到图形的顶部和右侧
ax.xaxis.tick_top()
ax.yaxis.tick_right()

# 设置标题和坐标轴的深度值
ax.title.set_zorder(1)
ax.xaxis.label.set_zorder(1)
ax.yaxis.label.set_zorder(1)
ax.xaxis.set_tick_params(pad=10, zorder=1)
ax.yaxis.set_tick_params(pad=10, zorder=1)

# 设置坐标轴投影线条的样式和深度值
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['top'].set_linestyle('-')
ax.spines['right'].set_linestyle('-')
ax.spines['top'].set_zorder(0)
ax.spines['right'].set_zorder(0)

plt.show()

 

 

5. Divide the window: subplot()

subplot(nrows, ncols, index, **kwargs)
  • nrows: the number of rows in the submap table;
  • ncols: the number of columns in the submap table;
  • index: The position of the subgraph in the table (number from left to right, top to bottom);
  • kwargs: Other optional parameters, such as axis scale, title, label font, etc.
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei,Times New Roman, Arial'#设置字体格式,显示中文、正负号,罗马数字
import matplotlib.pyplot as plt
import numpy as np

#生成数据
np.random.seed(2022)
x = np.linspace(0.0, 4.0*np.pi, 100)
y_sin = np.sin(x)
y_cos = np.cos(x)

# 绘制正弦函数
plt.subplot(2, 1, 1)
plt.plot(x, y_sin, 'g-', linewidth=2, label='sin(x)')
plt.legend(loc='upper right')
plt.title('Sin(x)与Cos(x)')

# 绘制余弦函数
plt.subplot(2, 1, 2)
plt.plot(x, y_cos, 'r-', linewidth=2, label='cos(x)')
plt.legend(loc='lower right')

plt.xlabel('X')

# 显示图像
plt.show()

Guess you like

Origin blog.csdn.net/weixin_49349476/article/details/131046975