Matplotlib构造子图(4)---图表对比

    xiaoxiao2021-04-15  398

    ''' 在matplot中,整个图像为一个Figure对象 每个Axes对象都是一个拥有自己坐标系统的绘图区域 plt.figure, plt.subplot ''' import numpy as np import pandas as pd import matplotlib.pyplot as plt % matplotlib inline #第一种子图的生成方法,--先建立子图然后填充图表--代码书写有一定的格式 plt.xkcd() # 子图创建 fig = plt.figure(figsize = (10, 6),facecolor = 'gray') ax1 = fig.add_subplot(2,2,1) plt.plot(np.random.rand(50).cumsum(), 'k--') plt.plot(np.random.randn(50).cumsum(), 'b--') ax2 = fig.add_subplot(2,2,2) ax2.hist(np.random.rand(50), alpha = 0.3) ax4 = fig.add_subplot(2,2,4) df2 = pd.DataFrame(np.random.randn(10, 4), columns = ['a','b','c','d']) ax4.plot(df2, alpha = 0.4) [<matplotlib.lines.Line2D at 0x2b8746417b8>, <matplotlib.lines.Line2D at 0x2b874641128>, <matplotlib.lines.Line2D at 0x2b874641f60>, <matplotlib.lines.Line2D at 0x2b8746416d8>]

    ''' fig------ax ax------xaxis, yaxis, title, data xaxis------tick, lable tick------tick, label yaxis------tick, label ''' '\nfig------ax\nax------xaxis, yaxis, title, data\nxaxis------tick, lable\ntick------tick, label\nyaxis------tick, label\n' #第二种创建子图的方法---创建一个新的figure返回一个subplot对象的numpy数组 --> plt.subplots fig, axes = plt.subplots(2,3,figsize = (10, 4)) ts = pd.Series(np.random.randn(1000).cumsum()) print(axes, axes.shape, type(axes)) #生成图表对象数组 ax1 = axes[0, 1] ax1.plot(ts) df = pd.DataFrame(np.random.randn(100,3)) df.plot(ax = axes[1,0]) # 用的更多一些 [[<matplotlib.axes._subplots.AxesSubplot object at 0x000002B8783C0EF0> <matplotlib.axes._subplots.AxesSubplot object at 0x000002B87840B128> <matplotlib.axes._subplots.AxesSubplot object at 0x000002B87842F400>] [<matplotlib.axes._subplots.AxesSubplot object at 0x000002B8784576D8> <matplotlib.axes._subplots.AxesSubplot object at 0x000002B87847D9E8> <matplotlib.axes._subplots.AxesSubplot object at 0x000002B8784A4C88>]] (2, 3) <class 'numpy.ndarray'> <matplotlib.axes._subplots.AxesSubplot at 0x2b8784576d8>

    plt.subplots(2,3,figsize = (10, 4)) (<Figure size 720x288 with 6 Axes>, array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000002B877083518>, <matplotlib.axes._subplots.AxesSubplot object at 0x000002B87708A5F8>, <matplotlib.axes._subplots.AxesSubplot object at 0x000002B87706AC18>], [<matplotlib.axes._subplots.AxesSubplot object at 0x000002B876F35208>, <matplotlib.axes._subplots.AxesSubplot object at 0x000002B876FA7518>, <matplotlib.axes._subplots.AxesSubplot object at 0x000002B876FD87B8>]], dtype=object))

    #plt.subplots,参数调整 fig, axes = plt.subplots(2,2,sharex = True, sharey = True) #sharex, sharey: 是否共享x,y刻度 for i in range(2): for j in range(2): axes[i, j].hist(np.random.randn(500),color = 'k', alpha = 0.4) plt.subplots_adjust(wspace = 0, hspace = 0) #wspace, hspace:用于控制宽与高的百分比,如subplot间的距离


    最新回复(0)