Python-数据分析工具3-Matplotlib

目录

一、布局

Figure()对象(画板)

subplots()对象(画纸)

subplots_adjust()(画纸布局)

二、轴相关

三、区间上下限

四、区间分段

五、实例  

1、线

2、散点图​    ​

3、条形图

4、直方图

5、饼图

1、箱形图

2、等高线(轮廓图)


一、布局

Figure()对象(画板)

subplots()对象(画纸)

def pylayout():
    '''2行2列第x个区域,构建一个坐标轴画板'''
    fig = plt.figure()
    ax1 = fig.add_subplot(221)
    ax2 = fig.add_subplot(222)
    ax3 = fig.add_subplot(223)
    '''2行2列4个区域,用数组形式对每个坐标轴画板操作'''
    fig, axes = plt.subplots(nrows=2, ncols=2)
    axes[0,0].set(title='Upper Left')
    axes[0,1].set(title='Upper Right')
    axes[1,0].set(title='Lower Left')
    axes[1,1].set(title='Lower Right')
    '''3个区域,默认行排列'''
    fig,(ax1,ax2,ax3)=plt.subplots(3)

    

subplots_adjust()(画纸布局)

1.通过fig.subplots_adjust()

修改了子图水平之间的间隔wspace=0.5。垂直方向上的间距hspace=0.3,左边距left=0.125 等等。

这里数值都是百分比的。以 [0, 1] 为区间,选择left、right、bottom、top 注意 top 和 right 是 0.9 表示上、右边距为百分之10。

2.通过fig.tight_layout()

自动调整子图参数.检查坐标轴标签、刻度标签以及标题的部分 。

之前说到了内边距,内边距是子图的,也就是 Axes 对象,所以这样使用 ax.margins(x=0.1, y=0.1),当值传入一个值时,表示同时修改水平和垂直方向的内边距。

fig, axes = plt.subplots(2, 2, figsize=(9, 9))
fig.subplots_adjust(wspace=0.5, hspace=0.3,
                    left=0.125, right=0.9,
                    top=0.9,    bottom=0.1)

#fig.tight_layout()
plt.show()

二、轴相关

    fig, ax = plt.subplots()
    ax.plot([-2, 2, 3, 4], [-10, 20, 25, 5])
    #顶边界不可见
    ax.spines['top'].set_visible(False)
    # ticks 的位置为下方,分上下的。     
    ax.xaxis.set_ticks_position('bottom') 
    #右边界不可见
    ax.spines['right'].set_visible(False)   
    ax.yaxis.set_ticks_position('left')  

    # "常规移动位置"
    # 移动左、下边界离 Axes 10 个距离
    ax.spines['bottom'].set_position(('outward', 10))
    ax.spines['left'].set_position(('outward', 10))

    # "百分比移动位置"
    # 移动边界,按 Axes 的百分比位置
    ax.spines['bottom'].set_position(('axes', 0.75))
    ax.spines['left'].set_position(('axes', 0.3))

    # "数轴相交位置"
    # 移动左、下边界到 (0, 0) 处相交
    ax.spines['bottom'].set_position(('data', 0))
    ax.spines['left'].set_position(('data', 0))

三、区间上下限

1.语法

ax.set_xlim([xmin, xmax])   #设置X轴的区间
ax.set_ylim([ymin, ymax])   #Y轴区间
ax.axis([xmin, xmax, ymin, ymax])   #X、Y轴区间
ax.set_ylim(bottom=-10)     #Y轴下限
ax.set_xlim(right=25)       #X轴上限

2.实例

def pyRange():
    x = np.linspace(0, 2*np.pi)
    y = np.sin(x)
    fig, (ax1, ax2) = plt.subplots(2)
    ax1.plot(x, y)
    ax2.plot(x, y)
    ax2.set_xlim([-1, 6])
    ax2.set_ylim([-1, 3])
    plt.show()

四、区间分段

def pyInterPara():
   #重命名,坐标轴刻度,中文不识别    
    data = [('断站告警', 2), ('小区告警', 3), ('高频告警', 1)]
    alarm, value = zip(*data)

    fig, (ax1, ax2) = plt.subplots(2)
    x = np.arange(len(alarm))
    ax1.bar(x, value, align='center', color='gray')
    ax2.bar(x, value, align='center', color='gray')

    ax2.set(xticks=x, xticklabels=alarm)
   #修改 ticks 的方向以及长度
    #ax.tick_params(axis='y', direction='inout', length=10)
    plt.show()

五、实例  

常规

1、线

plot函数的参数

def pyline():
   #np.pi 是一个常数表示圆周率π
    x = np.linspace(0, np.pi)
    y_sin = np.sin(x)
    y_cos = np.cos(x)
    
    fig = plt.figure()
    ax1 = fig.add_subplot(221)
    ax2 = fig.add_subplot(222)
    ax3 = fig.add_subplot(223)
   #颜色参数:Colors,点型参数Markers,线型参数Line Styles   
    ax1.plot(x, y_sin)
    ax2.plot(x, y_sin, 'go--', linewidth=1, markersize=6)
    ax3.plot(x, y_cos, color='red', marker='p', linestyle='dashed')

2、散点图

'''普通散点图'''
def pyscatter():
    x = np.arange(10)
    y = np.random.randn(10)
    plt.scatter(x, y, color='red', marker='o')
    plt.show()
'''泡泡图:加入了第三个值 s 可以理解成普通散点,但画的是二维,泡泡图体现了Z的大小'''
def pyscatter2():
   #seed( ) 用于指定随机数生成时所用算法开始的整数值。
    np.random.seed(9000)
    
    N=50
    x=np.random.rand(N)
    y=np.random.rand(N)
    
    colors=np.random.rand(N)
    area=(30*np.random.rand(N))**2
    
    plt.scatter(x,y,s=area,c=colors,alpha=0.5)
    plt.show()

    

3、条形图

def pybar():
  #0.设置seed,则每次生成的随机数也相同
    np.random.seed(1)
    x=np.arange(5)
    y=np.random.randn(5)
  #1.划分区域    
    fig,axes=plt.subplots(ncols=3,figsize=plt.figaspect(1./3))
  #2.设置每个区域的垂直 水平画布
    vert_bars=axes[0].bar(x,y,color='lightblue',align='center')
    horiz_bars=axes[1].barh(x,y,color='lightblue',align='center')
  #3.在垂直 水平方向上划线
    axes[0].axhline(0,color='gray',linewidth=2)    
    axes[1].axvline(0,color='gray',linewidth=2)
  #4.按条件设置柱状图颜色
    for bar, height in zip(vert_bars, y):
        if height < 0:
            bar.set(edgecolor='darkred', color='salmon', linewidth=3)
    plt.show()

4、直方图

hist函数的参数

条形图与直方图的区别:

1、条形图是用条形的高度表示频数的大小,而直方图实际上是用长方形的面积表示频数,当长方形的宽相等的时候可以用矩形的的高表示频数;

2、条形图中,横轴上的数据是孤立的,是一个具体的数据,而直方图中,横轴上的数据是连续的,是一个范围;

3、条形图中,各长方形之间有空隙,而直方图中,各长方形是靠在一起的

def pyhistogram():
    np.random.seed()
    
    n_bins=10   
    x=np.random.randn(1000,3)

    fig,axes=plt.subplots(nrows=2,ncols=2)
    ax0,ax1,ax2,ax3=axes.flatten()
  # 参数density 是否以密度的形式显示    
    colors=['red','tan','lime']
    ax0.hist(x,n_bins,density=True,histtype='bar',color=colors,label=colors)
    ax0.legend(prop={'size':10})
    ax0.set_title('bars with legend')
  # 参数histtype 线条的类型    
    ax1.hist(x,n_bins,density=True,histtype='barstacked')
    ax1.set_title('stacked bar')
    
    ax2.hist(x,histtype='barstacked',rwidth=0.9)
    
    ax3.hist(x[:,0],rwidth=0.9)
    ax3.set_title('different sample sizes')
  # tight_layout会自动调整子图参数.检查坐标轴标签、刻度标签以及标题的部分 
    fig.tight_layout()
    plt.show()

5、饼图

pie函数的参数

def pypie():
#中文字符不识别
#    labels='断站告警','小区告警','高频告警'
#    sizes=[15,30,55]
    
#标签和其所占百分比必须一一对应   
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    sizes=[15,30,45,10]
    explode=(0,0.1,0,0)
#labels:是各个块的标签
#autopct=%1.1f%%表示格式化百分比精确输出    
    fig1,(ax1,ax2)=plt.subplots(2)
    ax1.pie(sizes,labels=labels,autopct='%1.1f%%',shadow=True)
    ax1.axis('equal')
#explode:突出某些块,不同的值突出的效果不一样。
#pctdistance=1.12百分比距离圆心的距离,默认是0.6.
    ax2.pie(sizes,autopct='%1.2f%%',shadow=True,startangle=90,explode=explode,pctdistance=1.12)
    ax2.axis('equal')
#.legend各颜色所表示的标签放在右方显示
    ax2.legend(labels=labels,loc='upper right')
    
    plt.show()

特殊

1、箱形图

箱线图(boxplot)参数及分析详解

箱形图最重要的用途就是识别异常值。数据清洗中作用很大

def pybox():
    
    data = np.random.normal(size=(1000,4),loc=0,scale=1)
    labels = ['A','B','C','D']
    data2 = np.random.normal(size=1000,loc=0,scale=1)
    
    fig,(ax1,ax2)=plt.subplots(2)
    ax1.boxplot(data,labels=labels)
  # 修改箱型图的方向    
    ax2.boxplot(data2,vert=False)
    
    plt.show()

2、等高线(轮廓图)

contour 函数的用法

def pycontourl():
    fig,(ax1,ax2)=plt.subplots(2)
    x=np.arange(-5,5,0.1)
    y=np.arange(-5,5,0.1)
  # numpy.meshgrid()将原始数据变成网格数据形式,生成网格点坐标矩阵    
    xx,yy=np.meshgrid(x,y,sparse=True)
    z=np.sin(xx**2+yy**2)
  # contourf可以填充颜色,contour不填充颜色 
    ax1.contourf(x,y,z)
    ax2.contour(x,y,z)

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值