[Python matplotlib] fig, ax = plt.subplots() draw multi-table graphs

1. The role of fig, ax = plt.subplots()

It is used to create a total canvas/figure "window". If there is a figure, you can draw on the top (or one of the sub-grids/subplots) (fig: short for figure).

Second, the meaning of the parameters

fig = plt.figure()

matpltlib.pyplot.figure(
num = None,               # 设定figure名称。系统默认按数字升序命名的figure_num(透视表输出窗口)e.g. “figure1”。可自行设定figure名称,名称或是INT,或是str类型;
figsize=None,             # 设定figure尺寸。系统默认命令是rcParams["figure.fig.size"] = [6.4, 4.8],即figure长宽为6.4 * 4.8;
dpi=None,                 # 设定figure像素密度。系统默命令是rcParams["sigure.dpi"] = 100;
facecolor=None,           # 设定figure背景色。系统默认命令是rcParams["figure.facecolor"] = 'w',即白色white;
edgecolor=None, frameon=True,    # 设定要不要绘制轮廓&轮廓颜色。系统默认绘制轮廓,轮廓染色rcParams["figure.edgecolor"]='w',即白色white;
FigureClass=<class 'matplotlib.figure.Figure'>,   # 设定使不使用一个figure模板。系统默认不使用;
clear=False,                     # 设定当同名figure存在时,是否替换它。系统默认False,即不替换。
**kwargs)

ax = plt.subplot() [Official website link]

Three, arrange multiple subgraphs on the graph

For example, we want to draw a 2*2 subgraph, and each subgraph corresponds to a table.

  1. Create a multidimensional window:
fig, axes = plt.subplots(2, 2)  # 此处是一个2*2的图
  1. Set the position of each perspective sub-picture in the window:
data.plot.bar(ax=axes[1,1], color='b', alpha=0.5)  # ax=[1,1] 即位置是第2行、第二列。(python从0开始计数,所以“1”代表第2的)
 
data.plot.barh(ax=axes[0,1], color='k', alpha=0.5) # alpha:设定图表的透明度;
  1. Add sub-perspective code.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
 
fig, axes = plt.subplots(2, 2)
 
data = pd.Series(np.random.rand(16), index=list('abcdefghijklmnop'))
 
data.plot.bar(ax=axes[1,1], color='b', alpha = 0.5)
data.plot.barh(ax=axes[0,1], color='k', alpha=0.5)
 
plt.show()

Four, merge multiple sub-pictures together into one picture

The most important point is to let multiple graphs share the same x-coordinate axis.

  • The statement stipulates that N line graphs share one x coordinate (note: the y axis is divided into main and secondary axes):
import numpy as np
import matplotlib.pyplot as plt
 
fig, ax1 = plt.subplots(1, 1)             # 做1*1个子图,等价于 " fig, ax1 = plt.subplot() ",等价于 " fig, ax1 = plt.subplots() "
 
ax2 = ax1.twinx()                         # 让2个子图的x轴一样,同时创建副坐标轴。
 
# 作y=sin(x)函数
x1 = np.linspace(0, 4 * np.pi, 100)
y1 = np.sin(x1)
ax1.plot(x1, y1)
 
#  作y = cos(x)函数
x2 = np.linspace(0, 4 * np.pi, 100)       # 表示在区间[0, 4π]之间取100个点(作为横坐标,“线段是有无数多个点组成的”)。
y2 = np.cos(x2)
ax2.plot(x2, y2)
 
plt.savefig('sin_cos_2.png')               # 将窗口另存为png格式图片

Insert picture description here
If the primary and secondary y-axes are required to be the same: replace both ax1 and ax2 with ax.

  • Custom chart styles: such as rotating the x-axis label, the upper and right axes are not displayed, the curve and the y-axis are aligned, etc.
import matplotlib.pyplot as plt
 
plt.rcParams['font.family'] = ['SimHei']              # 解决不能输出中文的问题。不区分大小写,即SimHei’效果等价于‘simhei’,中括号可以不要
plt.rcParams['figure.autolayout'] = True              # 解决不能完整显示的问题(比如因为饼图太大,显示窗口太小)
  
fig, ax = plt.subplots(1, 1, figsize=(12, 9))         # 进一步设定fig的size为12*9
 
ax.spines['top'].set_visible(False)                   # 不显示图表框的上边框
ax.spines['right'].set_visible(False)                 # 不显示图表框的右边框
 
ax.set_xlim(0, 10)                                    # 有时候x轴不会从0显示,使得折线图和y轴有间隙
ax.set_ylim(0, 1.3e8)                                 # 和x轴同理
 
plt.xticks(range(0, 10), fontsize=12, rotation=80)    # 针对x轴的标签,指定我们想要设定的范围是(0, 10), 字体大小是12, 逆时针旋转80°
 
plt.tick_params(bottom='off', left='off', labelbottom='on', lableleft='on')  # 使x轴和y轴不带比例标识点, labelbottom设定下边、即x轴的标签是否显示。
 
< blabla... >
 
plt.suptitle('自定义图表', fontsize=400, ha='center')  # 即标题在x轴和y轴形成的方框内部,如下图(详细用法见下注释)。如果需要标题在这上方,使用 plt.title(blabla)            
plt.show()
"""
对于multiple subplots一般情况下,
1)设置 plt.xticks(range(0, 10))只会对最后一个ax起作用。要想作用于所有subplots,要这样:
for ax in axes:
    ax.set_xticks(range(0, 10))
2)标题:显示中文方面-在各个子图上要这样:
plt.title('某个子图的中文title', fontproperties='simhei'),
因为plt.rcParams['font.family'] = 'simhei' 只对整体的标题是有效的。
整体的标题要这样设置:
plt.suptitle(‘全体子图的中文title’)
3)xticks的旋转方面。例如上面的主副坐标轴的共x轴,要这样:
ax1.set_xticklabels(['str format labels'], rotation=80)
而这样的设置无效:plt.xticks(x, rotation=80)。
"""

Insert picture description here

matplotlib.pyplot.suptitle(
t,                          # text缩写。即标题文字。
fontsize | size,            # 设定字体大小。
x,                          # 设定标题相对于x轴的位置,默认是'0.5'。
y,                          # 设定标题相对于y轴的位置,默认是'0.98'。
ha | horizontalalignment,   # 和参数x一起使用,设定标题水平方位,默认是‘center’。共3个可选值{'center', 'left', right'}。
va | verticalalignment,     # 和参数y一起使用,设定标题垂直方位, 默认是'top'。共4个可选值{'top', 'center', 'bottom', 'baseline'}。
fontweight | weight         # 设定字体权重。
)

Five, drawing scale, legend and other fonts, font size, scale density, line style settings

  • Output image size:
figsize = 11,9
figure, ax = plt.subplots(figsize=figsize)
  • Draw a simple line chart, and mark the shape, name, and thickness of the line at the same time:
A,=plt.plot(x1,y1,'-r',label='A',linewidth=5.0,ms=10)

Among them, the line style and color settings can be referred to: Add link description . The line thickness is set using linewidth, and the size of the marker on the corresponding line is set to the ms parameter. Because sometimes thick lines, the corresponding marker size also needs to be increased. If you want to mark the marker as hollow, you can add markerfacecolor='none'

  • Set the legend and corresponding attributes:
legend = plt.legend(handles=[A,B],prop=font1)

The font format of the legend is set in prop. The assignment font1 can be a dictionary containing various attributes and their corresponding values. Attributes include family (font), size (font size) and other common attributes. For a more detailed explanation, please refer to the matplotlib manual. Explanation about the legend prop.

A relatively simple setting is:

font1 = {
    
    'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 23,
}
  • Axis scale density/interval setting: The numbers in parentheses are the corresponding scale interval values, and the y-axis corresponds similarly.
ax.xaxis.set_major_locator(MultipleLocator(10))
  • Axis scale value attribute setting:
plt.tick_params(labelsize=23)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]

Among them, a series of attributes can be set in tick_params, including a series of attributes such as scale value font size, direction, size, color, etc. For details, please refer to the explanation of tick_params in the manual.

The special thing is that there is no attribute to set the font of the scale value, so we need to use the following two lines to set it. In the initial use of plt.subplots, there is a return value ax. We use ax.get_xticklabels() and ax.get_yticklabels() to get all the tick values, and use the set_fontname function to set the attributes.

  • Axis name and corresponding font property settings:
plt.xlabel('round',font2)
plt.ylabel('value',font2)

This kind of comparison is simple, the first parameter is the axis name, and the second parameter is also a dictionary parameter, which has the same format as the dict font1 mentioned above.

Sometimes, because the font size of the coordinate scale is adjusted, the display of the coordinate axis label is affected. So we need to display the label by adjusting the axis margin

plt.subplots_adjust(left = 0.15,bottom=0.128)
#--coding:utf-8--
import  matplotlib.pyplot as plt
 
#数据设置
x1 =[0,5000,10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000];
y1=[0, 223, 488, 673, 870, 1027, 1193, 1407, 1609, 1791, 2113, 2388];
 
x2 =[0,5000,10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000];
y2=[0, 214, 445, 627, 800, 956, 1090, 1281, 1489, 1625, 1896, 2151];
 
#设置输出的图片大小
figsize = 11,9
figure, ax = plt.subplots(figsize=figsize)
 
#在同一幅图片上画两条折线
A,=plt.plot(x1,y1,'-r',label='A',linewidth=5.0)
B,=plt.plot(x2,y2,'b-.',label='B',linewidth=5.0)
 
#设置图例并且设置图例的字体及大小
font1 = {
    
    'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 23,
}
legend = plt.legend(handles=[A,B],prop=font1)
 
#设置坐标刻度值的大小以及刻度值的字体
plt.tick_params(labelsize=23)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
 
#设置横纵坐标的名称以及对应字体格式
font2 = {
    
    'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 30,
}
plt.xlabel('round',font2)
plt.ylabel('value',font2)
 
#将文件保存至文件中并且画出图
plt.savefig('figure.eps')
plt.show()

Insert picture description here

Guess you like

Origin blog.csdn.net/zou_albert/article/details/114887347