外贸网站建设优化推广,网站建设的总结与评价,网络营销的好处,织梦网站建设网页【1】引言
前述学习进程中#xff0c;对hist()函数画直方图已经有一定的探索。然而学无止境#xff0c;在继续学习的进程中#xff0c;我发现了一个显得函数subplot_mosaic()#xff0c;它几乎支持我们随心所欲地排布多个子图。
经过自我探索#xff0c;我有一些收获对hist()函数画直方图已经有一定的探索。然而学无止境在继续学习的进程中我发现了一个显得函数subplot_mosaic()它几乎支持我们随心所欲地排布多个子图。
经过自我探索我有一些收获写在这里和大家一起继续学习。
【2】官网教程
首先是进入官网点击下方链接直达
Complex and semantic figure composition (subplot_mosaic) — Matplotlib 3.9.2 documentation
在这里我们看到先用常规plot方法画出了两行两列的子图然后调用subplot_mosaic()输出了同样结果为此我们做一下代码解读。
【3】代码解读
在plot画子图的过程中调用了text()函数为避免偏离主题和带来疑惑我们主要集中精力探索下述代码段 fig plt.figure(layoutconstrained) ax_dict fig.subplot_mosaic( [ [bar, plot], [hist, image], ], ) ax_dict[bar].bar([a, b, c], [5, 7, 9]) ax_dict[plot].plot([1, 2, 3]) ax_dict[hist].hist(hist_data) ax_dict[image].imshow([[1, 2], [2, 1]]) identify_axes(ax_dict) 在这里我们看到定义了一个fig.subplot_mosaic()函数函数包括四个小项bar、plot、hist和image这四个小项提前占好了位置分别是
bar[1,1]
plot[1,2]
hist[2,1]
image[2,2]
真正执行将fig.subplot_mosaic()函数中的小项输出的操作是identify_axes(ax_dict)。
接下来我们回到identify_axes(ax_dict)函数的具体定义 def identify_axes(ax_dict, fontsize48):Helper to identify the Axes in the examples below.Draws the label in a large font in the center of the Axes.Parameters----------ax_dict : dict[str, Axes]Mapping between the title / label and the Axes.fontsize : int, optionalHow big the label should be. kw dict(hacenter, vacenter, fontsizefontsize, colordarkgrey)for k, ax in ax_dict.items():ax.text(0.5, 0.5, k, transformax.transAxes, **kw) 在这里 使用dict()函数进行了赋值操作虽然这个函数看起来很奇怪但是将其功能直接理解为赋值操作即可
之后使用k和ax在ax_dict 也就是 fig.subplot_mosaic()函数里面遍历实现将fig.subplot_mosaic()函数里面的小项输出。
运行代码后的输出图像为 图1
至此的完整代码为
import matplotlib.pyplot as plt #引入画图模块
import numpy as np #引入计算模块
np.random.seed(19680801) #定义随机数种子
hist_data np.random.randn(1_500) #定义随机数数组# Helper function used for visualization in the following examples
def identify_axes(ax_dict, fontsize48): #自定义函数该函数调用ax_dict作为输入参数Helper to identify the Axes in the examples below.Draws the label in a large font in the center of the Axes.Parameters----------ax_dict : dict[str, Axes]Mapping between the title / label and the Axes.fontsize : int, optionalHow big the label should be.kw dict(hacenter, vacenter, fontsizefontsize, colordarkgrey) #dict()也是一个函数就理解为是一个赋值操作即可for k, ax in ax_dict.items():#让k和ax在ax.dict()这个数组里面遍历ax.text(0.5, 0.5, k, transformax.transAxes, **kw) #调用text()函数将ax_dict中的项输出
fig plt.figure(layoutconstrained)
ax_dict fig.subplot_mosaic([[bar, plot],[hist, image],],)
ax_dict[bar].bar([a, b, c], [5, 7, 9]) #调用bar()函数输出直方图
ax_dict[plot].plot([1, 2, 3]) #调用plot()函数输出直线
ax_dict[hist].hist(hist_data) #调用hist()函数输出频数分布图
ax_dict[image].imshow([[1, 2], [2, 1]]) #调用imshow()函数填充区域
identify_axes(ax_dict) #调用自定义函数
plt.show() #输出图形
【4】代码修改
在前述内容中fig.subplot_mosaic()函数将子项分成了两行两列接下来我们将其改为一行 ax_dict fig.subplot_mosaic([[bar, plot,hist,image],#[ image],],) 此时的输出图像为 图2
然后再改为一列 ax_dict fig.subplot_mosaic([[bar],[plot],[hist],[image],],) 此时的输出图像为 图3
可见通过定义fig.subplot_mosaic()函数子项的位置可以直接影响subplot()子图的位置。
【5】总结
初步学习了fig.subplot_mosaic()函数设置多子图位置的方法。