资讯专栏INFORMATION COLUMN

Python+matplotlib绘制多子图的方法详解

89542767 / 610人阅读

  matplotlib作为一种常见的可视化图形操作软件,在日常的生活中应用还是比较的广泛的,下面跟着小编的视角,带着大家去详细解答Python+matplotlib绘制多子图的方法。


  本文速览


  matplotlib.pyplot api绘制子图

01.png

  面向对象方式绘制子图

02.png

  matplotlib.gridspec.GridSpec绘制子图

03.png

  任意位置添加子图

04.png

  关于pyplot和面向对象两种绘图方式可参考之前文章:matplotlib.pyplot api verus matplotlib object-oriented


  1、matplotlib.pyplot api方式添加子图


  import matplotlib.pyplot as plt
  my_dpi=96
  plt.figure(figsize=(480/my_dpi,480/my_dpi),dpi=my_dpi)
  plt.subplot(221)
  plt.plot([1,2,3])
  plt.subplot(222)
  plt.bar([1,2,3],[4,5,6])
  plt.title('plt.subplot(222)')#注意比较和上面面向对象方式的差异
  plt.xlabel('set_xlabel')
  plt.ylabel('set_ylabel',fontsize=15,color='g')#设置y轴刻度标签
  plt.xlim(0,8)#设置x轴刻度范围
  plt.xticks(range(0,10,2))#设置x轴刻度间距
  plt.tick_params(axis='x',labelsize=20,rotation=45)#x轴标签旋转、字号等
  plt.subplot(223)
  plt.plot([1,2,3])
  plt.subplot(224)
  plt.bar([1,2,3],[4,5,6])
  plt.suptitle('matplotlib.pyplot api',color='r')
  fig.tight_layout(rect=(0,0,1,0.9))
  plt.subplots_adjust(left=0.125,
  bottom=-0.51,
  right=1.3,
  top=0.88,
  wspace=0.2,
  hspace=0.2
  )
  #plt.tight_layout()
  plt.show()

05.png

  2、面向对象方式添加子图


  import matplotlib.pyplot as plt
  my_dpi=96
  fig,axs=plt.subplots(2,2,figsize=(480/my_dpi,480/my_dpi),dpi=my_dpi,
  sharex=False,#x轴刻度值共享开启
  sharey=False,#y轴刻度值共享关闭
  )
  #fig为matplotlib.figure.Figure对象
  #axs为matplotlib.axes.Axes,把fig分成2x2的子图
  axs[0][0].plot([1,2,3])
  axs[0][1].bar([1,2,3],[4,5,6])
  axs[0][1].set(title='title')#设置axes及子图标题
  axs[0][1].set_xlabel('set_xlabel',fontsize=15,color='g')#设置x轴刻度标签
  axs[0][1].set_ylabel('set_ylabel',fontsize=15,color='g')#设置y轴刻度标签
  axs[0][1].set_xlim(0,8)#设置x轴刻度范围
  axs[0][1].set_xticks(range(0,10,2))#设置x轴刻度间距
  axs[0][1].tick_params(axis='x',#可选'y','both'
  labelsize=20,rotation=45)#x轴标签旋转、字号等
  axs[1][0].plot([1,2,3])
  axs[1][1].bar([1,2,3],[4,5,6])
  fig.suptitle('matplotlib object-oriented',color='r')#设置fig即整整张图的标题
  #修改子图在整个figure中的位置(上下左右)
  plt.subplots_adjust(left=0.125,
  bottom=-0.61,
  right=1.3,#防止右边子图y轴标题与左边子图重叠
  top=0.88,
  wspace=0.2,
  hspace=0.2
  )
  #参数介绍
  '''
  ##The figure subplot parameters.All dimensions are a fraction of the figure width and height.
  #figure.subplot.left:0.125#the left side of the subplots of the figure
  #figure.subplot.right:0.9#the right side of the subplots of the figure
  #figure.subplot.bottom:0.11#the bottom of the subplots of the figure
  #figure.subplot.top:0.88#the top of the subplots of the figure
  #figure.subplot.wspace:0.2#the amount of width reserved for space between subplots,
  #expressed as a fraction of the average axis width
  #figure.subplot.hspace:0.2#the amount of height reserved for space between subplots,
  #expressed as a fraction of the average axis height
  '''
  plt.show()

 

06.png

    3、matplotlib.pyplot add_subplot方式添加子图


  my_dpi=96
  fig=plt.figure(figsize=(480/my_dpi,480/my_dpi),dpi=my_dpi)
  fig.add_subplot(221)
  plt.plot([1,2,3])
  fig.add_subplot(222)
  plt.bar([1,2,3],[4,5,6])
  plt.title('fig.add_subplot(222)')
  fig.add_subplot(223)
  plt.plot([1,2,3])
  fig.add_subplot(224)
  plt.bar([1,2,3],[4,5,6])
  plt.suptitle('matplotlib.pyplot api:add_subplot',color='r')

07.png

  4、matplotlib.gridspec.GridSpec方式添加子图


  语法:matplotlib.gridspec.GridSpec(nrows,ncols,figure=None,left=None,bottom=None,right=None,top=None,wspace=None,hspace=None,width_ratios=None,height_ratios=None)


  import matplotlib.pyplot as plt
  from matplotlib.gridspec import GridSpec
  fig=plt.figure(dpi=100,
  constrained_layout=True,#类似于tight_layout,使得各子图之间的距离自动调整【类似excel中行宽根据内容自适应】
  )
  gs=GridSpec(3,3,figure=fig)#GridSpec将fiure分为3行3列,每行三个axes,gs为一个matplotlib.gridspec.GridSpec对象,可灵活的切片figure
  ax1=fig.add_subplot(gs[0,0:1])
  plt.plot([1,2,3])
  ax2=fig.add_subplot(gs[0,1:3])#gs[0,0:3]中0选取figure的第一行,0:3选取figure第二列和第三列
  #ax3=fig.add_subplot(gs[1,0:2])
  plt.subplot(gs[1,0:2])#同样可以使用基于pyplot api的方式
  plt.scatter([1,2,3],[4,5,6],marker='*')
  ax4=fig.add_subplot(gs[1:3,2:3])
  plt.bar([1,2,3],[4,5,6])
  ax5=fig.add_subplot(gs[2,0:1])
  ax6=fig.add_subplot(gs[2,1:2])
  fig.suptitle("GridSpec",color='r')
  plt.show()

 

07.png

   5、子图中绘制子图


  import matplotlib.pyplot as plt
  import matplotlib.gridspec as gridspec
  def format_axes(fig):
  for i,ax in enumerate(fig.axes):
  ax.text(0.5,0.5,"ax%d"%(i+1),va="center",ha="center")
  ax.tick_params(labelbottom=False,labelleft=False)
  #子图中再绘制子图
  fig=plt.figure(dpi=100,
  constrained_layout=True,
  )
  gs0=GridSpec(1,2,figure=fig)#将figure切片为1行2列的两个子图
  gs00=gridspec.GridSpecFromSubplotSpec(3,3,subplot_spec=gs0[0])#将以上第一个子图gs0[0]再次切片为3行3列的9个axes
  #gs0[0]子图自由切片
  ax1=fig.add_subplot(gs00[:-1,:])
  ax2=fig.add_subplot(gs00[-1,:-1])
  ax3=fig.add_subplot(gs00[-1,-1])
  gs01=gs0[1].subgridspec(3,3)#将以上第二个子图gs0[1]再次切片为3行3列的axes
  #gs0[1]子图自由切片
  ax4=fig.add_subplot(gs01[:,:-1])
  ax5=fig.add_subplot(gs01[:-1,-1])
  ax6=fig.add_subplot(gs01[-1,-1])
  plt.suptitle("GridSpec Inside GridSpec",color='r')
  format_axes(fig)
  plt.show()
  6、任意位置绘制子图(plt.axes)
  plt.subplots(1,2,dpi=100)
  plt.subplot(121)
  plt.plot([1,2,3])
  plt.subplot(122)
  plt.plot([1,2,3])
  plt.axes([0.7,0.2,0.15,0.15],##[left,bottom,width,height]四个参数(fractions of figure)可以非常灵活的调节子图中子图的位置
  )
  plt.bar([1,2,3],[1,2,3],color=['r','b','g'])
  plt.axes([0.2,0.6,0.15,0.15],
  )
  plt.bar([1,2,3],[1,2,3],color=['r','b','g'])

10.png

  以上就是Python+matplotlib绘制多子图的方法详解的详细内容,希望可以给大家带来帮助。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/128335.html

相关文章

  • Python绘制数据动态图的方法详解

      小编写这篇文章的一个主要目的,主要是给大家去做一个介绍,介绍的内容是,利用Python这门语言,去绘制相关的数据动态图表,那么,具体的绘制方法是什么呢?下面小编就给大家详细的解答。  数据动态图怎么做,效果图,  多子图联动竞赛图  安装  pipinstallpandas_alive   #或者   condainstallpandas_alive-cconda-forge   玩起来  支...

    89542767 评论0 收藏0
  • 详解Pythonmatplotlib模块的绘图方式

      matplotlib作为常见的可视化绘图工具,在工作当中,应用还是比较的广泛的,那么,我们要怎么使用python这门语言去进行绘图呢?下面就给大家详细解答下。  1、matplotlib之父简介  matplotlib之父John D.Hunter已经去世,他的一生辉煌而短暂,但是他开发的的该开源库还在继续着辉煌。国内介绍的资料太少了,查阅了一番整理如下:  1968出身于美国的田纳西州代尔斯...

    89542767 评论0 收藏0
  • 仅需10道题轻松掌握Matplotlib图形处理 | Python技能树征题

    摘要:问题描述绘制函数上的点,请从以下选项中选出你认为正确的答案正确答案第题条形图的绘制知识点描述绘制条形图。 仅需10道题轻松掌握Matplotlib图形处理 | P...

    YorkChen 评论0 收藏0
  • Python数据分析:直方图及子图的绘制

    摘要:直方图的绘制也需要用到下的,只不过在绘制折线图时我们采用的是,而绘制直方图时我们需要采用。利用确定直方图轴的范围及间距,为最小值,为最大值,为间距。用绘制,为数据,为直方图的特性,可有可无。 1.直方图的绘制也需要用到matplotlib下的pylab,只不过在绘制折线图时我们采用的是plot(),而绘制直方图时我们需要采用hist()。由于在绘制过程中缺少真实数据,我在这里采用np....

    stonezhu 评论0 收藏0
  • 【数据科学系统学习】Python # 数据分析基本操作[三] matplotlib

    摘要:有一些表示常见图形的对象称为块,完整的集合位于。中的绘图函数在中,有行标签列标签分组信息。密度图通过计算可能会产生观测数据的连续概率分布的估计而产生的。在探索式数据分析工作中,同时观察一组变量的散布图是很有意义的。 我们在上一篇介绍了 pandas,本篇介绍 matplotlib。 绘图和可视化 一个用于创建出版质量图表的桌面绘图包。 Matplotlib API入门 Figure ...

    BDEEFE 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<