对数据需要进行一个简单可视化,考虑使用KDE和小提琴图,考虑到每次不同的绘图风格和图片文字大小,以及背景。我简单整理了一下绘制过程和细节,以我本次绘图为基准,整体代码如下。
1. 输入数据(输入的是二分类数据)
import pandas as pd
import numpy as np
data = pd.read_csv(r'C:\Users\d0.csv',index_col = 0)
data.head(5)#查看前五行数据
2. 提取需要使用的数据
Y0 = data[data['Y'] == 0]
Y1 = data[data['Y'] == 1]#首先将二分类数据分类取出
Y0_Ag = Y0['Age']
Y1_Ag = Y1['Age']#提取需要绘制的列数据
3. 绘制KDE图
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
sns.set_style("darkgrid"
#, {"axes.facecolor": "pink"}#修改背景色
)#设置背景
font1 = {'family' : 'Times New Roman'
,'weight' : 'normal'
}#定义一个字体
font2 = {'family' : 'Times New Roman'
,'weight' : 'normal'
,'size' : 18}#定义一个字体
# ax.set_xlim(0,50)
# ax.set_ylim(0,0.1)#设置X,Y轴范围
plt.figure(figsize=(12,9))#设置画布大小
ax = sns.kdeplot(Y0_Ag, color="Red", shade=True)
ax = sns.kdeplot(Y1_Ag, color="Blue", shade=True)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]#设置坐标刻度字体类型
plt.tick_params(labelsize=21)#同时设置X,Y轴刻度字体大小
ax.set_xlabel('Age',fontsize=25,fontproperties=font1)
ax.set_ylabel("Frequency",fontsize=25,fontproperties=font1)#设置X,Y轴Label字体类型
ax = ax.legend(["0","1"],prop=font2#设置legend字体类型
#,loc='best',edgecolor='blue'#修改legend位置和框线颜色
#,frameon=False #设置legend无框线
)
ax = plt.gca()
ax.spines['right'].set_color('grey')
ax.spines['left'].set_color('grey')
ax.spines['top'].set_color('grey')
ax.spines['bottom'].set_color('grey')#添加灰色边框线
#plt.savefig('G_Age_KDE.tiff',dpi=600)#保存图片,可以修改后缀更改格式
plt.show()
KDE结果如图:
4. 同理绘制小提琴图(修改一行代码即可)
修改:ax = sns.violinplot(x=data['Y'], y=data['Age'],data=data,palette="muted")
完整代码如下:
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
sns.set_style("darkgrid"
#, {"axes.facecolor": "pink"}#修改背景色
)#设置背景
font1 = {'family' : 'Times New Roman'
,'weight' : 'normal'
}#定义一个字体
# ax.set_xlim(0,50)
# ax.set_ylim(0,0.1)#设置X,Y轴范围
plt.figure(figsize=(12,9))#设置画布大小
ax = sns.violinplot(x=data['Y'], y=data['Age'],data=data,palette="muted")
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]#设置坐标刻度字体类型
plt.tick_params(labelsize=21)#同时设置X,Y轴刻度字体大小
ax.set_xlabel('Label',fontsize=25,fontproperties=font1)
ax.set_ylabel("Age",fontsize=25,fontproperties=font1)#设置X,Y轴Label字体类型
ax = plt.gca()
ax.spines['right'].set_color('grey')
ax.spines['left'].set_color('grey')
ax.spines['top'].set_color('grey')
ax.spines['bottom'].set_color('grey')#添加灰色边框线
#plt.savefig('G_Age_violin.tiff',dpi=600)#保存图片
plt.show()
以上,持续更新中...