美文网首页python 画图
python画图设置坐标轴的位置及角度及设置colorbar

python画图设置坐标轴的位置及角度及设置colorbar

作者: 单细胞空间交响乐 | 来源:发表于2020-11-08 15:30 被阅读0次

    用python画图

    设置y轴在右边显示

    f, ax = plt.subplots(figsize = (14, 10))
    sns.heatmap(corr,cmap='RdBu', linewidths = 0.05, ax = ax)
    ax.set_title('Correlation between features', fontsize=18, position=(0.5,1.05))

    将y轴或x轴进行逆序

    ax.invert_yaxis()

    ax.invert_xaxis()

    ax.set_xlabel('X Label',fontsize=10)

    设置Y轴标签的字体大小和字体颜色

    ax.set_ylabel('Y Label',fontsize=15, color='r')

    设置坐标轴刻度的字体大小

    matplotlib.axes.Axes.tick_params

    ax.tick_params(axis='y',labelsize=8) # y轴

    ax.tick_params(axis='x',labelsize=6, colors='b', labeltop=True, labelbottom=False) # x轴

    将x轴刻度放置在top位置的几种方法

    ax.xaxis.set_ticks_position('top')

    ax.xaxis.tick_top()

    ax.tick_params(axis='x',labelsize=6, colors='b', labeltop=True, labelbottom=False) # x轴

    修改tick的字体颜色

    ax.tick_params(axis='x', colors='b') # x轴

    旋转轴刻度上文字方向的两种方法

    ax.set_xticklabels(ax.get_xticklabels(), rotation=-90)

    ax.set_xticklabels(corr.index, rotation=90)

    单独设置y轴或x轴刻度的字体大小, 调整字体方向

    ax.set_yticklabels(ax.get_yticklabels(),fontsize=6)

    ax.set_xticklabels(ax.get_xticklabels(), rotation=-90)

    旋转轴刻度上文字方向的两种方法

    ax.set_xticklabels(ax.get_xticklabels(), rotation=-90)

    ax.set_xticklabels(corr.index, rotation=90)

    将x轴刻度放置在top位置的几种方法

    ax.xaxis.set_ticks_position('top')

    ax.xaxis.tick_top()

    ax.tick_params(axis='x',labelsize=6, colors='b', labeltop=True, labelbottom=False)

    import os
    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    import math
    import seaborn as sns
    import matplotlib.gridspec as mg
    from sklearn import preprocessing
    os.chdir('C:/Users/86178/Desktop')
    x = pd.read_table('TME_Sender.csv',index_col=20,sep = ',')
    x.iloc[:,0:20] = preprocessing.scale(x.iloc[:,0:20])
    y = pd.read_table('ligand_receptor_matrix.txt',sep = '\t',index_col = 0)
    z = pd.read_csv('TSK_receiver.csv',index_col= 0)
    z.iloc[:,0:22] = preprocessing.scale(z.iloc[:,0:22])
    z = z.T
    gs = mg.GridSpec(5, 5)
    plt.subplot(gs[0:4,1:4])
    zz = sns.heatmap(y,cmap='PuRd',linewidths= 1,yticklabels=False,cbar = False)
    zz.xaxis.set_ticks_position('top')
    zz.set_ylabel('')
    zz.set_xticklabels(zz.get_xticklabels(),rotation = 90,family = 'Times New Roman')
    plt.subplot(gs[4,1:4])
    a = sns.heatmap(x,cmap='bwr',linewidths= 1,xticklabels=False,cbar = False)
    a.yaxis.set_ticks_position('right')
    a.set_yticklabels(a.get_yticklabels(), rotation=0,family = 'Times New Roman')
    a.set_xticklabels(a.get_xticklabels(),family = 'Times New Roman')
    plt.ylabel('')
    plt.subplot(gs[:4,0])
    x = sns.heatmap(z,cbar = False,cmap = 'bwr')
    x.xaxis.set_ticks_position('top')
    x.set_xticklabels(x.get_xticklabels(),family = 'Times New Roman',rotation = 90)
    x.set_yticklabels(x.get_yticklabels(),family = 'Times New Roman')
    x.set_xlabel('')
    #x.xaxis.set_ticks_position('top')
    plt.show()
    
    图片1.png

    python设置colorbar

    自定义colorbar包含两方面:

    自定义colorbar的颜色组合及颜色占比
    自定义colorbar的位置和大小
    

    这两项比较简单和实用,matplotlib和seaborn都可以尝试。对于某些特殊的数据分布类型,想在一张图内显示的情况比较适合。
    cmap的自定义

    cmap本质是一个RGBA格式的颜色列表,元素类型为np.array() ,np.array()里包含4个0-1的元素,前3个是RGB值,第4个为透明度。

    seaborn取颜色列表可以用以下方式:

    sns.light_palette('blue',reverse=True,n_colors=5)
    plt.cm.get_cmap('Blues', 5)
    plt.cm.get_cmap('cubehelix', 5)
    

    如果数据中有两组相差比较大的数据构成,可考虑取两组颜色值合并,可通过n_colors参数控制两组颜色的占比,如果存在极值,极值可设置为特殊颜色。
    colorbar的位置和大小

    可以把colorbar作为单独的axes,自由地定义其位置和占图比例,例如colorbar可以这样设置:cbar_ax = fig.add_axes([0.7, 0.75, 0.025, 0.2]),在seaborn热图中有对应的参数接受自定义的colorbar。

    #!/usr/bin/env python
    # coding: utf-8 -*- 
    
    import pandas as pd
    import numpy as np
    ## 以下为MACOS设置,linux请改为 ​matplotlib.use('Agg')
    matplotlib.use('TkAgg')
    ## juypter notebook显示图像设置
    %matplotlib inline
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    cmap= sns.light_palette('blue',reverse=True,n_colors=5)
    cmap2=sns.light_palette('red',reverse=False,n_colors=15)
    cmap.extend(cmap2)
    cmap.append(np.array([.3,.7,.6,1]))
    cmap.insert(0,np.array([.7,.7,.5,1]))
    
    fig = plt.figure(figsize=(4,7))
    ax = fig.add_axes([0.38, 0.3, 0.3, 0.65], facecolor = 'white')
    cbar_ax = fig.add_axes([0.7, 0.75, 0.025, 0.2])
    
    df = pd.DataFrame(np.random.rand(12,5))
    ax = sns.heatmap(df, ax=ax,annot=False, cmap=cmap, linewidths=.5, cbar_ax = cbar_ax)
    

    下图的效果对比更明显


    图片.png

    画图时候marker参数的设置

    marker type 含义
    “.” point 点
    “,” pixel 像素
    “o” circle 圆
    “v” triangle_down 下三角
    “^” triangle_up 上三角
    “<” triangle_left 左三角
    “>” triangle_right 右三角
    “1” tri_down 类似奔驰的标志
    “2” tri_up 类似奔驰的标志
    “3” tri_left 类似奔驰的标志
    “4” tri_right 类似奔驰的标志
    “8” octagon 八角形
    “s” square 正方形
    “p” pentagon 五角星
    “*” star 星号
    “h” hexagon1 六边形1
    “H” hexagon2 六边形2
    “+” plus 加号
    “x” x x
    “D” diamond 钻石
    “d” thin_diamond 细的钻石
    “ “ vline
    “-“ hline 水平方向的线
    “TICKLEFT” octagon 像素

    去掉刻度线

    plt.tick_params(bottom=False,top=False,left=False,right=False)

    相关文章

      网友评论

        本文标题:python画图设置坐标轴的位置及角度及设置colorbar

        本文链接:https://www.haomeiwen.com/subject/qkkavktx.html