seaborn绘图

官方文档:https://www.cntofu.com/book/172/docs/43.md

主要用到以下包

import matplotlib.pyplot as plt
import seaborn as sns

记性不好,每次画图都要重新看文档,总结一下,包括一些设置,会不断更新。

通用设置

1. 风格

    darkgrid(灰底网格)
    whitegrid(白底网格)
    dark(灰底)
    white(白底)
    ticks(会把X轴和Y轴的刻度线画出来)

sns.set(style="whitegrid",font_scale=1.4)    ##font_scale 会把X Y轴刻度及标题字体都修改

或者

sns.set_style("white")

one_sample=list(np.random.randint(30,size=100))
sns.set(style="whitegrid",font_scale=1.4)
ax = sns.distplot( one_sample,kde=False,bins= np.arange(0,30,1),
                  hist_kws={ "linewidth": 0, "alpha": 1, "color": "#7995c4"})
ax.set_xlabel('random int',fontsize=15)
ax.set_ylabel('count',fontsize=15)
ax.set_title('')
ax.set_xlim(0,30)

 sns.despine()   会只保留X  Y轴线

2. X坐标轴标签

ax.set_xticklabels(labels=[-10,0,10,20,40],fontsize=30)

one_sample=list(np.random.randint(30,size=100))
sns.set(style="white",font_scale=1.4)
ax = sns.distplot( one_sample,kde=False,bins= np.arange(0,30,1),
                  hist_kws={ "linewidth": 0, "alpha": 1, "color": "#7995c4"})

 

sns.set(style="white",font_scale=1.4)
ax = sns.distplot( one_sample,kde=False,bins= np.arange(0,30,1),
                  hist_kws={ "linewidth": 0, "alpha": 1, "color": "#7995c4"})
ax.set_xticklabels(['1','2','3','4','5','6','7','8'],fontsize=15)

 

3. legend图例

 handles, labels = ax.get_legend_handles_labels()

ax.legend(handles, labels,loc='right',bbox_to_anchor=(1.2,0.5), ncol=1)

handles:legend形状

labels:legend文字

可以对其进行排序,但是需要注意的是,handles,labels排序需要一起排 

ncol:表示legend分成几列,太长了可以设置这个值

loc跟bbox_to_anchor: 联合设置legend位置

 排序之前

def draw_scatter_shape(draw_df,ylabel,imgname):
    breaks=["group1","group2",'group3']

    values=["red", "blue","green"]

    fig = plt.figure(figsize=(25, 8))
    
    pal = dict(zip(breaks, values))
    sns.set(style="whitegrid",font_scale=1.4)

    ax = sns.scatterplot(data=draw_df, x='sam', y='value',palette =pal,style = 'group',
                         hue='group',size='group',sizes=(170,180))

draw_scatter_shape(draw_df,'','')

 

def draw_scatter_shape(draw_df,ylabel,imgname):
    breaks=["group1","group2",'group3']

    values=["red", "blue","green"]

    fig = plt.figure(figsize=(25, 8))
    
    pal = dict(zip(breaks, values))
    sns.set(style="whitegrid",font_scale=1.4)

    ax = sns.scatterplot(data=draw_df, x='sam', y='value',palette =pal,style = 'group',
                         hue='group',size='group',sizes=(170,180))

    handles, labels = ax.get_legend_handles_labels()
    print(labels)
   
    group_order=['group2','group1','group3']

    labels, handles = zip(*sorted(zip(labels, handles), key=lambda t:group_order.index(t[0])))
    print(handles)
    
    ax.legend(handles, labels,loc='right',bbox_to_anchor=(1.1,0.5), ncol=1)
    fig.show()

draw_scatter_shape(draw_df,'','')

 

4子图

一、柱状图

数据格式如下

breaks=["sam020","sam025","sam044"]
values=[ "#666666","#009933", "#FF9933"]
pal = dict(zip(breaks, values))

###设置图长宽大小
fig = plt.figure(figsize=(8, 5))
###设置绘图风格
sns.set_style("whitegrid")
###为每个sample设置对应颜色
ax = sns.barplot( data=draw_df, x='sample', y='value',palette =pal )
###设置X\Y标签
ax.set_xlabel('value',fontsize=15)
ax.set_ylabel('',fontsize=15)
fig.show()

二、density

数据格式如下

代码

import seaborn as sns

fig = plt.figure(figsize=(10, 5))
###hist表示是否要画标准化直方图,rug为是否在横轴绘制观测值竖线
sns.distplot(draw_df['value'],hist=False,rug=False)

 

fig = plt.figure(figsize=(10, 5))
sns.distplot(draw_df['value'],hist=False,rug=True)

 

三、组合图

数据格式如下

graph = sns.jointplot(data=draw_df,x='value', y='value2')
####这里可以在散点图上画拟合曲线
graph.ax_joint.plot(draw_df['value'],2*draw_df['value'],'b-')

plt.suptitle('hhh')
r, p = stats.pearsonr(draw_df['value'], draw_df['value2'])

phantom, = graph.ax_joint.plot([], [], linestyle="", alpha=0)
graph.ax_joint.legend([phantom],['r={:f}, p={:f}'.format(r,p)])

plt.show()

四、双坐标轴

数据格式如下

fig = plt.figure(figsize=(8, 4))
ax = fig.add_subplot(111)
ax.plot('value3','value',data=draw_df,linewidth=2,color='blue')
ax.axhline(y = 20,color='#669999',linestyle='--')  #水平线

ax2 = ax.twinx()
ax2.scatter('value3','value2',data=draw_df,color='red')
ax.set_ylabel('value',fontsize=15,color='blue')
ax2.set_ylabel('value2',fontsize=15,color='red')
fig.legend(loc=1)

五、distplot

ax = sns.distplot( one_sample,kde=False,color='#7995c4',bins= np.arange(0,30,1))
ax.set_xlabel('random int',fontsize=15)
ax.set_ylabel('count',fontsize=15)
ax.set_title('')
ax.set_xlim(0,30)

 

 需要注意的是,这样画出来的柱子边缘会有白线,一旦柱子密集了蓝色就不明显了,可以通过以下方式去掉

ax = sns.distplot( one_sample,kde=False,bins= np.arange(0,30,1),
                  hist_kws={ "linewidth": 0, "alpha": 1, "color": "#7995c4"})
ax.set_xlabel('random int',fontsize=15)
ax.set_ylabel('count',fontsize=15)
ax.set_title('')
ax.set_xlim(0,30)

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晏九

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值