官方文档: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)