ggstatsplot- 做图与统计一块做了

前言

所谓一图胜千言: ""Information-rich graphic is worth a thousand words""
ggstatsplot的理念非常简单:把数据的可视化与统计分析一块做了
简单易用: ggplot2很强大, 但是,但是,太多的参数,细节。。,统计知识比较差的你表示:(
--ggstatsplot 就是你的救星了。。。

image.png

1. 软件安装

Install the ggstatsplot package from CRAN:

utils::install.packages("ggstatsplot")

Then you can get the development version of the package from Github:

library(remotes)remotes::install_github("IndrajeetPatil/ggstatsplot", dependencies = FALSE)

Load the needed packages-

library(ggstatsplot)library(ggplot2)

You are recommended to use the RStudioIDE, but you don't have to.

2. 使用

2.1 ggbetweenstats:分组数据分析

2.1.1 ggbetweenstats - defaults

ggbetweenstats(
  data = movies_long,
  x = mpaa, # > 2 groups
  y = rating,
  type = "p", # default
  messages = FALSE
)
image.png

Changing the type of test

  • "p" → parametric
  • "np" → non-parametric
  • "r" → robust
  • "bf" → bayes factor

2.1.2. ggbetweenstats - little code, rich details

ggbetweenstats(
  data = movies_long,
  x = mpaa,
  y = rating
)
image.png

Default information:

  • statistical details
  • Bayes Factor
  • sample sizes
  • distribution summary

2.1.3. ggbetweenstats - pairwise comparisons

ggbetweenstats(
  data = movies_long,
  x = mpaa,
  y = rating,
  type = "np",
  mean.ci = TRUE,
  pairwise.comparisons = TRUE,
  pairwise.display = "ns",
  p.adjust.method = "fdr",
  messages = FALSE
)
image.png

Changing pairwise comparisons displayed

  • "ns" → only non-significant
  • "s" → only significant
  • "all" → everything

2.1.4. ggbetweenstats - (aesthetic) changes & outlier

ggbetweenstats(
  data = movies_long,
  x = mpaa,
  y = rating,
  type = "r",
  conf.level = 0.99,
  pairwise.comparisons = TRUE,
  pairwise.annotation = "p", 
  outlier.tagging = TRUE,
  outlier.label = title,
  outlier.coef = 2,
  ggtheme = hrbrthemes::theme_ipsum_tw(),
  palette = "Darjeeling2",
  package = "wesanderson",
  messages = FALSE
)

Aesthetic preferences are not an excuse to not use ggstatsplot 😻
The default palette used is colorblind-

2.1.5. ggbetweenstats - modification with ggplot2

ggbetweenstats(
  data = movies_long,
  x = mpaa,
  y = rating,
  type = "bf",
  messages = FALSE
) + 
  scale_y_continuous(sec.axis = dup_axis())

https://indrajeetpatil.github.io/ggstatsplot_slides/slides/ggstatsplot_presentation_files/figure-html/ggbetweenstats_4-1.png

Note: You can modify all ggstatsplot plots further using ggplot2 functions. Yaay!

2.1.6. Summary of tests - ggbetweenstats

image.png

Effect sizes + CI - ggbetweenstats


image.png

Pairwise comparion tests - ggbetweenstats


image.png

2.2. ggwithinstats :分组、条件数据分析,

For within group/condition comparisons

2.2.1. ggwithinstats - repeated measures equivalent

ggwithinstats(
  data = WRS2::WineTasting,
  x = Wine,
  y = Taste,
  pairwise.comparisons = TRUE,
  pairwise.annotation = "p",
  ggtheme = hrbrthemes::theme_ipsum_tw(),
  ggstatsplot.layer = FALSE,
  messages = FALSE
)
image.png

Changing the type of test

  • "p" → parametric
  • "np" → non-parametric
  • "r" → robust
  • "bf" → bayes factor

2.2.2. ggwithinstats - little code, rich details

ggwithinstats(
  data = WRS2::WineTasting,
  x = Wine, # > 2 groups
  y = Taste,
  pairwise.comparisons = TRUE,
  pairwise.annotation = "p",
  ggtheme = hrbrthemes::theme_ipsum_tw(),
  ggstatsplot.layer = FALSE,
  messages = FALSE
)

Default information:

  • statistical details
  • pairwise comparisons
  • sample sizes
  • distribution summary

2.2.3. ggwithinstats - two groups,

ggwithinstats(
  data = iris_long,
  x = attribute, # 2 groups
  y = value,
  type = "r",
  messages = FALSE
)

Changing the type of test

  • "p" → parametric
  • "np" → non-parametric
  • "r" → robust
  • "bf" → bayes factor

2.3 ggscatterstats-散点图,双变量相关性分析

Association between two numeric variables

2.3.1 ggscatterstats - defaults

ggscatterstats(
  data = movies_long,
  x = budget,
  y = rating,
  type = "p", # default #<<<
  conf.level = 0.99,
  messages = FALSE
)
image.png

Changing the type of test

  • "p" → parametric
  • "np" → non-parametric
  • "r" → robust
  • "bf" → bayes factor

2.3.2. ggscatterstats - little code, rich details

ggscatterstats(
  data = movies_long,
  x = budget,
  y = rating,
  conf.level = 0.99
)

Default information:

  • distribution
  • Bayes Factor
  • statistical details

2.3.3. ggscatterstats - conditional point tagging

ggscatterstats(
  data = movies_long,
  x = budget,
  y = rating,
  type = "r", 
  centrality.para = "mean",
  label.var = title,
  label.expression = budget > 150
                     & rating > 7.5,
  marginal.type = "density",
  messages = FALSE
)

Changing the marginal type

  • histogram
  • boxplot
  • density
  • violin
  • densigram

2.3.4. ggscatterstats - changing smoothing functions

gscatterstats(
  data = movies_long,
  x = budget,
  y = rating,
  marginal = FALSE,  
  method = "gam",
  formula = y ~ s(x, k = 3),
  centrality.para = "mean",
  messages = FALSE
)

Available centrality parameters

  • mean
  • median

2.4 ggcorrmat :数据交叉相关性分析

2.4.1. ggcorrmat - defaults

ggcorrmat(
  data = ggplot2::msleep,
  cor.vars = sleep_cycle:bodywt,
  type = "r",
  matrix.type = "upper",
  p.adjust.method = "holm",
  colors = NULL,
  package = "yarrr",
  palette = "southpark"
)
image.png

Changing the type of test

  • "p" → parametric
  • "np" → non-parametric
  • "r" → robust
  • "bf" → not implemented

2.4.2. ggcorrmat - little code, rich details

ggcorrmat(data = dplyr::starwars)
image.png

Default information:
statistical details
sample sizes
details about test
Note: Informative label about sample sizes in case NAs are present.

2.4.4. ggcorrmat - changing defaults

ggcorrmat(
  data = ggplot2::msleep,
  cor.vars = sleep_cycle:bodywt,
  type = "r",
  matrix.type = "upper",
  p.adjust.method = "holm",
  colors = NULL,
  package = "yarrr",
  palette = "southpark"
)
image.png

In addition to output = "plot", this function can also be used to get a dataframe of results:

  • "r" → correlation
  • "p" → p-values
    -"n" → sample sizes
  • "ci" → confidence intervals

2.4.5. ggcorrmat - dataframe outputs

correlation coefficients

  data = ggplot2::msleep,
  cor.vars = sleep_cycle:bodywt,
  type = "np",
  output = "r",
  p.adjust.method = "fdr",
  messages = FALSE
)

** p-values**

ggcorrmat(
  data = ggplot2::msleep,
  cor.vars = sleep_cycle:bodywt,
  type = "np",
  output = "p",
  p.adjust.method = "none",
  messages = FALSE
)
image.png

** sample sizes**

ggcorrmat(
  data = ggplot2::msleep,
  cor.vars = sleep_cycle:bodywt,
  type = "np",
  output = "n",
  p.adjust.method = "fdr",
  messages = FALSE
)

image.png

confidence intervals

options(digits = 3)
ggcorrmat(
  data = ggplot2::msleep,
  cor.vars = awake:bodywt,
  type = "np",
  output = "ci",
  p.adjust.method = "fdr",
  messages = FALSE
)
image.png

2.5 gghistostats:密度图

Distribution of a numeric variable

2.5.1

2.5.2. gghistostats - further customization

gghistostats(
  data = movies_long,    
  x = budget,
  effsize.type = "d",
  test.value = 50,
  bar.measure = "mix",
  centrality.para = "median", 
  test.value.line = TRUE,
  normal.curve = TRUE,
  ggtheme = hrbrthemes::theme_ipsum_tw(), 
  ggstatsplot.layer = FALSE, 
  messages = FALSE
)
image.png

Available bar measures

  • count
  • proportion
  • both (of the above)
  • density

2.5.3. gghistostats - little code, rich details

gghistostats(
  data = movies_long,    
  x = budget,
  effsize.type = "d",
  test.value = 50,
  test.value.size = TRUE, 
  bar.measure = "mix", 
  centrality.para = "median", 
  test.value.line = TRUE,
  normal.curve = TRUE
)
image.png

Default information:

  • statistical details
  • Bayes Factor
  • frequency
  • distribution summary

2.6. ggdotplotstats- 点图

Distribution of a numeric variable with labels

2.6.1. ggdotplotstats - defaults

ggdotplotstats(
  data = movies_long,
  x = budget,
  y = genre,
  effsize.type = "d", 
  test.value = 52,
  centrality.para = "median", 
  test.value.line = TRUE,
  test.value.color = "red", 
  ggtheme = ggthemes::theme_par(),
  messages = FALSE
)
image.png

Changing the type of test

  • "p" → parametric
  • "np" → non-parametric
  • "r" → robust
  • "bf" → bayes factor

2.6.2. ggdotplotstats - little code, rich details

ggdotplotstats(
  data = movies_long,
  x = budget,
  y = genre,
  effsize.type = "d",
  test.value = 52,     
  centrality.para = "median", 
  test.value.line = TRUE, 
  test.value.color = "red"
)
image.png

Default information:

  • statistical details
  • Bayes Factor
  • distribution summary

2.6.3 Summary of tests - gghistostats/ggdotplotstats

image.png

2.7 ggpiestats: 饼图

For composition of categorical variables

2.7.1 ggpiestats - defaults

# let's use subset of data
ggpiestats(
  data = dplyr::filter(.data = movies_long, 
  genre %in% c("Drama", "Comedy", "Animated")), 
  x = genre,
  y =  mpaa,
  paired = FALSE, # default
  conf.level = 0.99,
  package = "ggsci",
  palette = "default_ucscgb",
  messages = FALSE
)
image.png

Test by design

  • paired = FALSE → Pearson's χ2
  • paired = TRUE → McNemar

2.7.2 ggpiestats - little code, rich details

# let's use subset of data
ggpiestats(
  data = dplyr::filter(movies_long, 
  genre %in% c("Drama", "Comedy", "Animated")), 
  x = genre,
  y =  mpaa,
  conf.level = 0.99
)
image.png

Default information:

  • statistical details
  • Bayes Factor
  • sample sizes
  • proportion test results

2.7.3 ggpiestats - proportion test

ggpiestats(
  data = as.data.frame(Titanic), 
  x = Survived,
  counts = Freq,
  slice.label = "both",
  messages = FALSE
)
image.png

Note: If the data is in tabled format, you can use the counts argument.
Test by analysis

  • condition != NULL → contingency table
  • y = = NULL → goodness of fit

2.8. ggbarstats: 条形图-不同变量比较

For composition of categorical variables

2.8.1 ggbarstats - defaults

ggbarstats(
  data = movies_long, 
  x = genre,
  y =  mpaa,
  paired = FALSE, # default
  package = "ggsci",
  palette = "default_igv",
  caption = substitute(
    paste(italic("Source"), ": www.imdb.com")
  ),
  messages = FALSE
)
image.png

Note: Even if you display Bayes Factor message in a caption, you can still use the caption argument.
Label information

  • percentage (default)
  • counts
  • both (of the above)

2.8.2. ggbarstats - little code, rich details

ggbarstats(
  data = movies_long, 
  x = genre,
  y =  mpaa
)
image.png

Default information:

  • statistical details
  • Bayes Factor
  • sample sizes
  • proportion test results

2.8.3 Test summary - ggpiestats/ggbarstats

image.png

2.9. ggcoefstats: 数据拟合、建模

Displaying results from regression analyses

2.9.1 ggcoefstats - defaults

# model
mod <- stats::aov(
  formula = rating ~ mpaa * genre,
  data = movies_long
)
# plot
ggcoefstats(x = mod)
image.png

In addition to output = "plot", this function can also be used to get a dataframe of results:

  • "tidy" → estimates
  • "glance" → model summary
  • "augment" → predictions

2.9.2 ggcoefstats - little code, rich details

Default information:

  • estimate + 95% CI
    -model summary
  • statistical details


    image.png

2.9.3. ggcoefstats - dataframe outputs

model summary

library(lme4)
# model
mod1 <- 
  lme4::lmer(formula = Reaction ~ Days + (Days | Subject),
             data = sleepstudy)
# dataframe
ggcoefstats(x = mod1, 
            output = "glance")

image.png

augmented dataframe

library(ordinal)
# model
mod2 <- clm(formula = rating ~ temp * contact, 
            data = wine)
# dataframe
ggcoefstats(x = mod2, 
            output = "augment") %>%
  head(5)
image.png

2.9.4. ggcoefstats: Supported models

image.png

2.9.5. ggcoefstats: If not implemented, use a dataframe

# dataframe with results
df <- tibble::tribble(
  ~term, ~estimate, ~std.error, ~statistic, ~p.value,
  "(Intercept)", 3.77, 0.165, 22.9, 1.49e-20,
  "x", -1.36, 0.258, -5.26, 1.13e-5
)
# plot
# `statistic` argument decides label format
ggcoefstats(
  x = df,
  statistic = "z",
  exclude.intercept = FALSE
)

Supported statistic (for dataframe objects):

  • t
    -z
  • F
    At the minimum, two columns needed - term and estimate.

2.9.6 ggcoefstats: You can also do meta-analysis!

# made up data
meta_df <- tibble::tribble(
  ~term, ~estimate, ~std.error,
  "study_1", 0.111, 0.065,
  "study_2", -0.003, 0.258,
  "study_3", 0.001, 0.120,
  "study_4", 0.032, 0.022,
  "study_5", -0.765, 0.650,
  "study_6", -0.032, 0.058
)
# plot
ggcoefstats(
  x = meta_df,
  meta.analytic.effect = TRUE,
  bf.message = TRUE,
  xlab = "estimate"
)
image.png

Frequentist random-effects meta-analysis from metafor
Bayesian random-effects meta-analysis from metaBMA

2.10. grouped_ variants of all functions

Running the same function for all levels of a single grouping variable

2.10.1. grouped_ functions

# only one additional argument
grouped_ggpiestats(
  data = mtcars, 
  x = cyl,
  grouping.var = am,
  results.subtitle = FALSE,
  messages = FALSE
)
image.png

vailable grouped_ variants

  • grouped_ggdotplotstats
  • grouped_ggbarstats
  • grouped_ggscatterstats
  • grouped_gghistostats
  • grouped_ggpiestats
  • grouped_ggbetweenstats
  • grouped_ggwithinstats
  • grouped_ggcorrmat

2.11 Utility beyond ggstatsplot

What if I don't like the default plots but still want to display statistical results?

2.11.1 Using as helper functions

ggstatsplot can also be used just to get the statistical details.

# using `ggstatsplot` for stats
results <- 
  ggstatsplot::ggpiestats(  
  data = Titanic_full,
  x = Survived,
  y =  Sex,
  return = "subtitle",
  messages = FALSE
)
# using `ggiraphExtra` for plot
ggiraphExtra::ggSpine(
  data = Titanic_full,
  aes(x = Sex, fill = Survived),
  addlabel = TRUE,
  interactive = FALSE
) + labs(subtitle = results)
image.png

All included analyses have their corresponding helper functions for preparing subtitles with statistical details.

2.12 Glossary

Statistical reporting in ggstatsplot

2.12.1. Best practices in reporting statistical details

  • As discussed before, the details included in statistical analyses follow the APA gold standard.
  • The default tests follow the best practices. For example, ggbetweenstats function by default runs Welch's t-test and Welch's ANOVA - and not Student's t-test and Fisher's ANOVA - based on recent work (Delacre et al., 2017, 2018).
  • No p-value error
    (Lilienfeld et al., 2015)

2.12.2 Avoiding errors

Since the plot and the statistical analysis are yoked together, the chances of making an error in reporting the results are minimized. You never have to write the results manually or copy-paste them from someplace else.


image.png

2.12.3 Making sense of null results

Combination of frequentist and Bayesian statistics for each analysis to properly interpret the null results.


image.png

2.12.4. Toggling between type of statistics

image.png

3. Types of statistical analyses supported

image.png

4. Effect sizes + CI available?

image.png

5. Benefits of using ggstatsplot

Truly makes your figures worth a thousand words.
No need to copy-paste results to the text editor (MS-Word, e.g.).
Disembodied figures stand on their own and are easy to evaluate for the reader.
More breathing room for theoretical discussion and other text.
No need to worry about updating figures and statistical details separately if something about the data changes.
Minimal amount of code needed for all functions (typically only data, x, and y). This minimizes chances of error.

6. Limitations

Limited kinds of plots available.
Limited number of statistical tests (and effect sizes) available.
Faceting (or small multiples) not implemented.
Default plots can be too complicated for effectively communicating results in time-constrained presentation settings (e.g., conference talks).

Bulky API (in terms of number of function arguments to keep in mind).
(Saving grace: Defaults are sufficient most of the time.)

7. Exhaustive documentation at the dedicated website-

https://indrajeetpatil.github.io/ggstatsplot/

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,123评论 6 490
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,031评论 2 384
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,723评论 0 345
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,357评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,412评论 5 384
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,760评论 1 289
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,904评论 3 405
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,672评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,118评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,456评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,599评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,264评论 4 328
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,857评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,731评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,956评论 1 264
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,286评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,465评论 2 348

推荐阅读更多精彩内容