python绘制云雨图raincloud plot


Posted in Python onAugust 05, 2022

官方github: https://github.com/RainCloudPlots/RainCloudPlots

Raincloud 的 Python 实现是一个名为 PtitPrince 的包,它写在 seaborn 之上,这是一个 Python 绘图库,用于从 pandas 数据帧中获取漂亮的绘图。

import pandas as pd
import seaborn as sns
import os
import matplotlib.pyplot as plt
#sns.set(style="darkgrid")
#sns.set(style="whitegrid")
#sns.set_style("white")
sns.set(style="whitegrid",font_scale=2)
import matplotlib.collections as clt
import ptitprince as pt
#图片保存及输出设置
savefigs = True
figs_dir = '../figs/tutorial_python'
if savefigs:
    # Make the figures folder if it doesn't yet exist
    #如果没有找到文件夹,先创建此文件夹
    if not os.path.isdir('../figs/tutorial_python'):
        os.makedirs('../figs/tutorial_python')

def export_fig(axis,text, fname):
    if savefigs:
        axis.text()
        axis.savefig(fname, bbox_inches='tight')
df = pd.read_csv ("simdat.csv", sep= ",")
df.head()

python绘制云雨图raincloud plot

该图可以让读者初步了解数据集:哪个组的平均值更大,这种差异是否可能显着。 此图中仅显示每组分数的平均值和标准差。

f, ax = plt.subplots(figsize=(7, 7))
sns.barplot(x = "group", y = "score", data = df, capsize= .1)
plt.title("Figure P1\n Bar Plot")
if savefigs:
    plt.savefig('.\\figs\\tutorial_python\\figureP01.png', bbox_inches='tight')

python绘制云雨图raincloud plot

为了了解我们的数据集的分布,我们可以绘制一个“云”,即直方图的平滑版本:

# plotting the clouds
f, ax = plt.subplots(figsize=(7, 5))
dy="group" 
dx="score"
ort="h"
pal = sns.color_palette(n_colors=1)
ax=pt.half_violinplot(x=dx, y=dy, data=df, palette=pal, bw=.2, cut=0., scale="area", width=.6, inner=None, orient=ort)
plt.title("Figure P2\n Basic Rainclouds")
if savefigs:
    plt.savefig('.\\figs\\tutorial_python\\figureP02.png', bbox_inches='tight')

python绘制云雨图raincloud plot

为了更精确地了解分布并说明数据中的潜在异常值或其他模式,我们现在添加“雨”,即数据点的简单单维表示:

# adding the rain
f, ax=plt.subplots(figsize=(7, 5))
ax=pt.half_violinplot(x=dx, y=dy, data=df, palette=pal, bw=.2, cut=0., scale="area", width=.6, inner=None, orient=ort)
ax=sns.stripplot(x=dx, y=dy, data=df, palette=pal, edgecolor="white", size=3, jitter=0, zorder=0, orient=ort)
plt.title("Figure P3\n Raincloud Without Jitter")
if savefigs:
    plt.savefig('.\\figs\\tutorial_python\\figureP03.png', bbox_inches='tight')

python绘制云雨图raincloud plot

# adding jitter to the rain
f, ax =plt.subplots(figsize=(7, 5))
ax=pt.half_violinplot(x=dx, y=dy, data=df, palette=pal, bw=.2, cut=0., scale="area", width=.6, inner=None, orient=ort)
ax=sns.stripplot(x=dx, y=dy, data=df, palette=pal, edgecolor="white", size=3, jitter=1, zorder=0, orient=ort)
plt.title("Figure P4\n Raincloud with Jittered Data")
if savefigs:
    plt.savefig('.\\figs\\tutorial_python\\figureP04.png', bbox_inches='tight')

python绘制云雨图raincloud plot

这样可以很好地了解数据点的分布情况,但中位数和四分位数并不明显,很难一目了然地确定统计差异。 因此,我们添加了一个“空”箱线图来显示中位数、四分位数和异常值:

#adding the boxplot with quartiles
f, ax=plt.subplots(figsize=(7, 5))
ax=pt.half_violinplot(x=dx, y=dy, data=df, palette=pal, bw=.2, cut=0.,
                      scale="area", width=.6, inner=None, orient=ort)
ax=sns.stripplot(x=dx, y=dy, data=df, palette=pal, edgecolor="white",
                 size=3, jitter=1, zorder=0, orient=ort)
ax=sns.boxplot(x=dx, y=dy, data=df, color="black", width=.15, zorder=10,
               showcaps=True, boxprops={'facecolor':'none',"zorder":10},
               showfliers=True, whiskerprops{'linewidth':2,"zorder":10},
               saturation=1, orient=ort)
plt.title("Figure P5\n Raincloud with Boxplot")
if savefigs:
    plt.savefig('../figs/tutorial_python/figureP05.png', bbox_inches='tight')

python绘制云雨图raincloud plot

现在我们可以设置一个调色板来表征两组:

#adding color
pal="Set2"
f, ax=plt.subplots(figsize=(7, 5))
ax=pt.half_violinplot(x=dx, y=dy, data=df, palette=pal, bw=.2, cut=0.,
                      scale="area", width=.6, inner=None, orient=ort)
ax=sns.stripplot(x=dx, y=dy, data=df, palette=pal, edgecolor="white",
                 size=3, jitter=1, zorder=0, orient=ort)
ax=sns.boxplot(x=dx, y=dy, data=df, color="black", width=.15, zorder=10,
              showcaps=True, boxprops={'facecolor':'none',"zorder":10},
              showfliers=True, whiskerprops={'linewidth':2,"zorder":10},
              saturation=1, orient=ort)
plt.title("Figure P6\n Tweaking the Colour of Your Raincloud")

python绘制云雨图raincloud plot

我们可以使用函数 pt.Raincloud 来添加一些自动化:

#same thing with a single command: now x **must** be the categorical value
dx="group"; dy="score"; ort="h"; pal="Set2"; sigma=.2
f, ax=plt.subplots(figsize=(7, 5))
pt.RainCloud(x=dx, y=dy, data=df, palette=pal, bw=sigma,
             width_viol = .6, ax = ax, orient = ort)
plt.title("Figure P7\n Using the pt.Raincloud function")
if savefigs:
    plt.savefig('../figs/tutorial_python/figureP07.png', bbox_inches='tight')

python绘制云雨图raincloud plot

‘move’ 参数可用于移动箱线图下方的雨量,在某些情况下提供更好的原始数据可见性:

#moving the rain below the boxplot
dx="group"; dy="score"; ort="h"; pal="Set2"; sigma=.2
f,ax=plt.subplots(figsize=(7, 5))
ax=pt.RainCloud(x=dx, y=dy, data=df, palette=pal, bw=sigma,
                 width_viol=.6, ax=ax, orient=ort, move=.2)
plt.title("Figure P8\n Rainclouds with Shifted Rain")

python绘制云雨图raincloud plot

此外,raincloud 函数同样适用于列表或 np.array,如果您更喜欢使用它们而不是数据框输入:

# Usage with a list/np.array input
dx=list(df["group"]); dy=list(df["score"])
f, ax=plt.subplots(figsize=(7, 5))
ax=pt.RainCloud(x=dx, y=dy, palette=pal, bw=sigma,
                 width_viol=.6, ax=ax, orient=ort)
plt.title("Figure P9\n Rainclouds with List/Array Inputs")

python绘制云雨图raincloud plot

对于某些数据,您可能希望将雨云的方向翻转为“petit prince”图。 您可以使用 pt.RainCloud 函数中的 ‘orient’ 标志来执行此操作:

# Changing orientation
dx="group"; dy="score"; ort="v"; pal="Set2"; sigma=.2
f, ax=plt.subplots(figsize=(7, 5))
ax=pt.RainCloud(x=dx, y=dy, data=df, palette=pal, bw=sigma,
                 width_viol=.5, ax=ax, orient=ort)
plt.title("Figure P10\n Flipping your Rainclouds")

python绘制云雨图raincloud plot

还可以更改用于生成数据概率分布函数的平滑核。 为此,您调整 sigma 参数:

#changing cloud smoothness
dx="group"; dy="score"; ort="h"; pal="Set2"; sigma=.05
f, ax=plt.subplots(figsize=(7, 5))
ax=pt.RainCloud(x=dx, y=dy, data=df, palette=pal, bw=sigma,
                 width_viol=.6, ax=ax, orient=ort)
plt.title("Figure P11\n Customizing Raincloud Smoothness")

python绘制云雨图raincloud plot

最后,使用 pointplot 标志,您可以添加一条连接组平均值的线。 这对于更复杂的数据集很有用,例如重复测量或因子数据。 下面我们通过改变各个图的色调、不透明度或闪避元素来说明使用雨云绘制此类数据的几种不同方法:

#adding a red line connecting the groups' mean value (useful for longitudinal data)
dx="group"; dy="score"; ort="h"; pal="Set2"; sigma=.2
f, ax=plt.subplots(figsize=(7, 5))
ax=pt.RainCloud(x=dx, y=dy, data=df, palette=pal, bw=sigma,
                 width_viol=.6, ax=ax, orient=ort, pointplot=True)
plt.title("Figure P12\n Adding Lineplots to Emphasize Factorial Effects")

python绘制云雨图raincloud plot

另一个灵活的选择是使用 Facet Grids 来分隔不同的组或因子水平,

如下所示:

# Rainclouds with FacetGrid
g=sns.FacetGrid(df, col="gr2", height=6)
g=g.map_dataframe(pt.RainCloud, x="group", y="score", data=df, orient="h")
g.fig.subplots_adjust(top=0.75)
g.fig.suptitle("Figure P13\n Using FacetGrid for More Complex Designs",  fontsize=26)

python绘制云雨图raincloud plot

作为一种替代方法,可以使用色调输入将不同的子组直接绘制在彼此之上,从而促进它们的比较:

# Hue Input for Subgroups
dx="group"; dy="score"; dhue="gr2"; ort="h"; pal="Set2"; sigma=.2
f, ax=plt.subplots(figsize=(12, 5))
ax=pt.RainCloud(x=dx, y=dy, hue=dhue, data=df, palette=pal, bw=sigma,
                 width_viol=.7, ax=ax, orient=ort)
plt.title("Figure P14\n Rainclouds with Subgroups")

python绘制云雨图raincloud plot

为了提高该图的可读性,我们使用相关标志(0-1 alpha 强度)调整 alpha 级别:

# Setting alpha level
f, ax=plt.subplots(figsize=(12, 5))
ax=pt.RainCloud(x=dx, y=dy, hue=dhue, data=df, palette=pal, bw=sigma,
                 width_viol=.7, ax=ax, orient=ort , alpha=.65)
plt.title("Figure P15\n Adjusting Raincloud Alpha Level")

python绘制云雨图raincloud plot

我们可以将 dodge 标志设置为 true,而不是让两个箱线图相互混淆,从而增加交互性:

#The Doge Flag
f, ax=plt.subplots(figsize=(12, 5))
ax=pt.RainCloud(x=dx, y=dy, hue=dhue, data=df, palette=pal, bw=sigma,
                 width_viol=.7, ax=ax, orient=ort , alpha=.65, dodge=True)
plt.title("Figure P16\n The Boxplot Dodge Flag")

python绘制云雨图raincloud plot

最后,我们可能希望在我们的图表中添加一个传统的线图,以帮助检测因子主效应和交互作用。

例如,我们在每个箱线图中绘制了平均值:

#same, with dodging and line
f, ax=plt.subplots(figsize=(12, 5))
ax=pt.RainCloud(x=dx, y=dy, hue=dhue, data=df, palette=pal, bw=sigma, 
                width_viol=.7, ax=ax, orient=ort , alpha=.65, 
                dodge=True, pointplot=True)
plt.title("Figure P17\n Dodged Boxplots with Lineplots")

python绘制云雨图raincloud plot

这是相同的图,但现在使用“移动”参数再次将单个观测值移动到箱线图下方:

#moving the rain under the boxplot
f, ax=plt.subplots(figsize=(12, 5))
ax=pt.RainCloud(x=dx, y=dy, hue=dhue, data=df, palette=pal, bw=sigma, 
               width_viol=.7, ax=ax, orient=ort , alpha=.65, dodge=True, 
               pointplot=True, move=.2)
plt.title("Figure P18\n Shifting the Rain with the Move Parameter")

python绘制云雨图raincloud plot

作为我们的最后一个示例,我们将考虑具有两组和三个时间点的复杂重复测量设计。 目标是说明我们复杂的相互作用和主要影响,同时保持雨云图的透明性:

# Load in the repeated data
df_rep=pd.read_csv("repeated_measures_data.csv", sep=",")
df_rep.columns=["score",  "timepoint", "group"]
df_rep.head()

python绘制云雨图raincloud plot

# Plot the repeated measures data
dx="group"; dy="score"; dhue="timepoint"; ort="h"; pal="Set2"; sigma=.2
f, ax=plt.subplots(figsize=(12, 5))
ax=pt.RainCloud(x=dx, y=dy, hue=dhue, data=df_rep, palette=pal, bw=sigma, width_viol=.7,
               ax=ax, orient=ort , alpha=.65, dodge=True, pointplot=True, move=.2)
plt.title("Figure P19\n Repeated Measures Data - Example 1")

python绘制云雨图raincloud plot

# Now with the group as hue
dx="timepoint"; dy="score"; dhue="group"
f, ax=plt.subplots(figsize=(12, 5))
ax=pt.RainCloud(x=dx, y=dy, hue=dhue, data=df_rep, palette=pal, bw=sigma, width_viol=.7,
                ax=ax, orient=ort , alpha=.65, dodge=True, pointplot=True, move=.2)
plt.title("Figure P20\n  Repeated Measures Data - Example 2")

python绘制云雨图raincloud plot

到此这篇关于python绘制云雨图raincloud plot的文章就介绍到这了,更多相关python绘制云雨图内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python安装Imaging报错:The _imaging C module is not installed问题解决方法
Aug 22 Python
Python中使用异常处理来判断运行的操作系统平台方法
Jan 22 Python
python基于socket实现网络广播的方法
Apr 29 Python
python之Socket网络编程详解
Sep 29 Python
python实现用户管理系统
Jan 10 Python
python简单操作excle的方法
Sep 12 Python
python 找出list中最大或者最小几个数的索引方法
Oct 30 Python
Python实现高斯函数的三维显示方法
Dec 29 Python
python机器人运动范围问题的解答
Apr 29 Python
Python 私有化操作实例分析
Nov 21 Python
python实现小世界网络生成
Nov 21 Python
详解python方法之绑定方法与非绑定方法
Aug 17 Python
python计算列表元素与乘积详情
Aug 05 #Python
Pygame游戏开发之太空射击实战敌人精灵篇
Aug 05 #Python
python playwrigh框架入门安装使用
Jul 23 #Python
python playwright之元素定位示例详解
Jul 23 #Python
Sentry的安装、配置、使用教程(Sentry日志手机系统)
Jul 23 #Python
Python中的 No Module named ***问题及解决
Jul 23 #Python
利用Python脚本写端口扫描器socket,python-nmap
Jul 23 #Python
You might like
PHPThumb图片处理实例
2014/05/03 PHP
PHP面向对象详解(三)
2015/12/07 PHP
php微信公众号js-sdk开发应用
2016/11/28 PHP
PHP实现微信模拟登陆并给用户发送消息的方法【文字,图片,图文】
2017/06/29 PHP
PHP利用递归函数实现无限级分类的方法
2019/03/22 PHP
准确获得页面、窗口高度及宽度的JS
2006/11/26 Javascript
JavaScript高级程序设计(第3版)学习笔记7 js函数(上)
2012/10/11 Javascript
关于js注册事件的常用方法
2013/04/03 Javascript
防止浏览器记住用户名及密码的简单实用方法
2013/04/22 Javascript
js判断鼠标同时离开两个div的思路及代码
2013/05/31 Javascript
AJAX和jQuery动态加载数据的实现方法
2016/12/05 Javascript
走进AngularJs之过滤器(filter)详解
2017/02/17 Javascript
angular-ngSanitize模块-$sanitize服务详解
2017/06/13 Javascript
axios中cookie跨域及相关配置示例详解
2017/12/20 Javascript
详解Chart.js轻量级图表库的使用经验
2018/05/22 Javascript
bootstrap table.js动态填充单元格数据的多种方法
2019/07/18 Javascript
Vue组件通信入门之Provide和Inject机制
2019/12/29 Javascript
Element Backtop回到顶部的具体使用
2020/07/27 Javascript
Echarts在Taro微信小程序开发中的踩坑记录
2020/11/09 Javascript
python实现上传样本到virustotal并查询扫描信息的方法
2014/10/05 Python
Python基于socket模块实现UDP通信功能示例
2018/04/10 Python
Caffe均值文件mean.binaryproto转mean.npy的方法
2018/07/09 Python
Python中logging.NullHandler 的使用教程
2018/11/29 Python
Python sklearn KFold 生成交叉验证数据集的方法
2018/12/11 Python
浅谈Pandas:Series和DataFrame间的算术元素
2018/12/22 Python
TensorFlow加载模型时出错的解决方式
2020/02/06 Python
Python编程快速上手——Excel到CSV的转换程序案例分析
2020/02/28 Python
8款精美的CSS3表单设计(登录表单/下拉选择/按钮附演示及源码)
2013/02/04 HTML / CSS
美国网上鞋子零售商:Dr. Scholl’s Shoes
2017/11/17 全球购物
集中采购方案
2014/06/10 职场文书
毕业证代领委托书
2014/09/26 职场文书
2015年物资管理工作总结
2015/05/20 职场文书
pytorch model.cuda()花费时间很长的解决
2021/06/01 Python
python 进阶学习之python装饰器小结
2021/09/04 Python
Python干货实战之八音符酱小游戏全过程详解
2021/10/24 Python
Python调用腾讯API实现人脸身份证比对功能
2022/04/04 Python