
代码绘制成果展示












代码解释


第一部分

# =========================================================================================# ====================================== 1. 环境设置 =======================================# =========================================================================================import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.patches import Patch

第二部分

# =========================================================================================# ======================================2.颜色库=======================================# =========================================================================================COLOR_SCHEMES = {1: ['#F08B94', '#C92B38', '#6E9AB7', '#165785'],}

第三部分

# =========================================================================================# ======================================3.小提琴图绘制函数=======================================# =========================================================================================def plot_half_violin(ax, #坐标轴data,#数据pos, #位置side='left', #方向color_fill='blue',#填充颜色color_edge='blue'): #边缘颜色#设定保留左半侧if side == 'left':vertices[:, 0] = np.clip(vertices[:, 0], -np.inf, pos) #将顶点X轴坐标限制在负无穷到中心位置之间else:vertices[:, 0] = np.clip(vertices[:, 0], pos, np.inf)

第四部分

# =========================================================================================# ======================================4.箱线图样式设置辅助函数=======================================# =========================================================================================def style_boxplot(bp, edge_color, fill_color): #箱线图对象、边缘颜色和填充颜色# 遍历箱线图须线、帽线和中位线for element in ['whiskers', 'caps', 'medians']:box.set(color=edge_color, #边缘颜色linewidth=1.5) #边缘线粗细box.set(facecolor=fill_color) #填充颜色

第五部分

# =========================================================================================# ======================================5.主绘图函数=======================================# =========================================================================================def plot_raincloud_chart(df, scheme_id):colors = COLOR_SCHEMES[scheme_id] #提取配色方案for spine in ax.spines.values():spine.set_linewidth(1.5)#配置坐标轴刻度ax.tick_params(axis='both', #x、ywhich='major', #主刻度length=6, #长width=1.5, #宽labelsize=12) #字体大小

第六部分

base_pre = 1.0 #左侧图x轴基准位置#调用小提琴图绘制函数plot_half_violin(ax,virginica_pre,pos=base_pre - 0.2,side='left',color_fill=color_virgi_fill,color_edge=color_virgi_edge)ax.scatter(jitter_versi_pre, #xversicolor_pre, #yfacecolors=color_versi_fill, #填充颜色edgecolors=color_versi_edge, #边缘颜色linewidths=1, #边缘线宽alpha=1, #透明度s=40, #大小zorder=2) #层# 样式调整style_boxplot(bp2,color_virgi_edge,color_virgi_fill)

第七部分

base_post = 2.0 #右侧图x轴基准位置#Virginica右侧箱线图x位置pos_box_virgi_post = base_post - 0.18#Versicolor右侧箱线图x位置pos_box_versi_post = base_post - 0.08#绘制箱线图bp4 = ax.boxplot([versicolor_post], #数据positions=[pos_box_versi_post], #xwidths=0.06, #宽patch_artist=True, #颜色填充showfliers=False) #离群值plot_half_violin(ax,virginica_post,pos=base_post + 0.2,side='right', color_fill=color_virgi_fill,color_edge=color_virgi_edge)#Versicolor右侧小提琴图plot_half_violin(ax,versicolor_post,pos=base_post + 0.2,side='right',color_fill=color_versi_fill,color_edge=color_versi_edge)

第八部分

#Versicolor数据均值mean_versi_pre, mean_versi_post = np.mean(versicolor_pre), np.mean(versicolor_post)ax.plot([pos_box_virgi_pre, pos_box_virgi_post], #x[mean_virgi_pre, mean_virgi_post],#ycolor=color_virgi_edge, #颜色marker='D', #均值点形状markersize=6, #点大小linewidth=1.5, #线宽zorder=3) #层

第九部分

#X轴刻度线位置ax.set_xticks([(base_pre + 0.04), (base_post - 0.04)])# X轴刻度标注ax.set_xticklabels(['Pre', 'Post'], #文本fontsize=12, #字体大小fontweight='bold') #加粗ax.spines['top'].set_visible(False) #隐藏ax.spines['right'].set_visible(False)ax.spines['left'].set_position(('outward', 10)) #移动ax.spines['bottom'].set_position(('outward', 10))ax.spines['bottom'].set_bounds((base_pre + 0.04), (base_post - 0.04)) #范围ax.spines['left'].set_bounds(2.0, 4.5)

第十部分

#实例化图例legend_elements = [#绘制图例ax.legend(handles=legend_elements, #句柄title='Flower Species', #标题loc='upper right', #位置bbox_to_anchor=(1.15, 1.05), #坐标frameon=False, #边框title_fontsize=12, #标题大小fontsize=11) #文本大

第十一部分

# =========================================================================================# ======================================2.颜色库=======================================# =========================================================================================if __name__ == '__main__':excel_filename = r"data.xlsx"#原始数据df_real = pd.read_excel(excel_filename)#读取plot_all = True#是否批量绘图if plot_all:for scheme_id in COLOR_SCHEMES.keys():selected_hex_colors = COLOR_SCHEMES[scheme_id]print(f'正在绘制并保存配色方案:{scheme_id}')plot_raincloud_chart(df_real, scheme_id)else:scheme_id = 1selected_hex_colors = COLOR_SCHEMES[scheme_id]print(f'正在绘制并保存方案:{scheme_id}')plot_raincloud_chart(df_real, scheme_id)

如何应用到你自己的数据

1.设置原始数据的保存路径,执行部分:
excel_filename = r"F:\公众号素材\20260612-配对云雨图\simulated_iris_data.xlsx"#原始数据2.设置是否进行批量绘图,执行部分:
plot_all = True#是否批量绘图3.设置要读取的数据列名,执行部分:
versicolor_pre = df['Versicolor_Pre'].dropna().valuesversicolor_post = df['Versicolor_Post'].dropna().valuesvirginica_pre = df['Virginica_Pre'].dropna().valuesvirginica_post = df['Virginica_Post'].dropna().values
4.设置绘图结果的保存地址,执行部分:
plt.savefig(fr"raincloud_plot_scheme_{scheme_id}.pdf", bbox_inches='tight')
推荐


获取方式
