SCI,CCF,EI以及核心期刊绘图宝典,爆款更新,助力科研!
本期分享:
【SCI绘图】【箱型图系列1】多类对比+各类下属子类对比
文末附带完整代码:
1.环境准备
python 3
from matplotlib import pyplot as plt
from scipy import stats
import pandas as pd
import numpy as np
import seaborn as sns
sns.set_theme()
sns.set_style('ticks')
plt.rc('figure', dpi=300)
plt.rc('font', size=8, family='Times New Roman')
plt.rc('axes', labelsize=8, linewidth=1)
plt.rc('xtick', labelsize=8)
plt.rc('xtick.major', size=3, width=1, pad=1.5)
plt.rc('ytick', labelsize=8)
plt.rc('ytick.major', size=3, width=1, pad=1.5)
plt.rc('legend', fontsize=8)
2.示例数据
seaborn.load_dataset返回一个Dataframe,定义如下
seaborn.load_dataset(name, cache=True, data_home=None, **kws)
# 此处可进行修改为自己的数据
penguins = sns.load_dataset("penguins")
penguins.head()
sex类别有Male和Female两类
3.绘图展示
定义绘图函数boxplot
def boxplot(fig):
ax = fig.subplots()
# island为横轴标签类别,body_mass_g为纵轴数值,而sex为各标签类别下的两个子类(Male和Female)
sns.boxplot(
data=penguins, x="island", y="body_mass_g", hue="sex", showfliers=False, linewidth=1, width=0.618
)
ax.set(xlabel="island", ylabel="body mass (g)")
ax.legend(ncol=2, loc="lower center", bbox_to_anchor=(0.5, 1), frameon=False)
sns.despine(ax=ax)
执行绘图
fig = plt.figure(figsize=(7.2 / 2, 7.2 / 2))
boxplot(fig)
fig.show()
完整代码如下:
from matplotlib import pyplot as plt
from scipy import stats
import pandas as pd
import numpy as np
import seaborn as sns
sns.set_theme()
sns.set_style('ticks')
plt.rc('figure', dpi=300)
plt.rc('font', size=8, family='Times New Roman')
plt.rc('axes', labelsize=8, linewidth=1)
plt.rc('xtick', labelsize=8)
plt.rc('xtick.major', size=3, width=1, pad=1.5)
plt.rc('ytick', labelsize=8)
plt.rc('ytick.major', size=3, width=1, pad=1.5)
plt.rc('legend', fontsize=8)
penguins = sns.load_dataset("penguins")
penguins.head()
def boxplot(fig):
ax = fig.subplots()
# island为横轴标签类别,body_mass_g为纵轴数值,而sex为各标签类别下的两个子类(Male和Female)
sns.boxplot(
data=penguins, x="island", y="body_mass_g", hue="sex", showfliers=False, linewidth=1, width=0.618
)
ax.set(xlabel="island", ylabel="body mass (g)")
ax.legend(ncol=2, loc="lower center", bbox_to_anchor=(0.5, 1), frameon=False)
sns.despine(ax=ax)
fig = plt.figure(figsize=(7.2 / 2, 7.2 / 2))
boxplot(fig)
fig.show()