今天给大家推荐一个专门用于不确定性可视化的绘图工具-R,可以方便的绘制一些统计图表的相关指标。详细介绍如下:
ungeviz包的目的是为ggplot2提供有用的附加功能,以实现不确定性的可视化。该软件包特别关注假设结果图(HOPs),并提供自举和抽样功能,与ggplot2的API很好地整合。
devtools::install_github("wilkelab/ungeviz")
ungeviz包中的sampler()和bootstrapper()函数分别生成采样和引导对象,在ggplot2图层中代替数据使用。这些对象在创建HOPs时很有帮助。
library(ggplot2)
library(dplyr)
library(forcats)
library(ungeviz)
library(gganimate)
cacao %>% filter(location %in% c("Canada", "U.S.A.")) %>%
ggplot(aes(rating, location)) +
geom_point(
position = position_jitter(height = 0.3, width = 0.05),
size = 0.4, color = "#0072B2", alpha = 1/2
) +
geom_vpline(data = sampler(25, group = location), height = 0.6, color = "#D55E00") +
theme_bw() +
# `.draw` is a generated column indicating the sample draw
transition_states(.draw, 1, 3)
Example01 of ungeviz
可以对数据拟合一个平滑模型,然后通过从后验分布中随机抽取产生拟合线,而不是对平滑器或回归线进行引导。可使用stat_smooth_draws()中是自动化完成的,其工作原理与stat_smooth()类似,但生成的是多个可能性相同的拟合线,而不是一条最佳拟合线。
ggplot(mtcars, aes(hp, mpg)) +
geom_point() +
stat_smooth_draws(times = 20, aes(group = stat(.draw))) +
theme_bw() +
transition_states(stat(.draw), 1, 2) +
enter_fade() + exit_fade()
Example02 of ungeviz
在可视化不确定性时,提供了一些几何图形和统计数字,包括上面抽样例子中使用的geom_hpline()和geom_vpline(),以及可以绘制置信度条的stat_confidence_density()。
library(broom)
library(emmeans)
cacao_lumped <- cacao %>%
mutate(
location = fct_lump(location, n = 20)
)
cacao_means <- lm(rating ~ location, data = cacao_lumped) %>%
emmeans("location") %>%
tidy() %>%
mutate(location = fct_reorder(location, estimate))
ggplot(cacao_means, aes(x = estimate, moe = std.error, y = location)) +
stat_confidence_density(fill = "lightblue", height = 0.8, confidence = 0.68) +
geom_point(aes(x = estimate), size = 2) +
geom_errorbarh(aes(xmin = estimate - std.error, xmax = estimate + std.error), height = 0.5) +
xlim(2.6, 3.7) +
theme_minimal()
Example03 of ungeviz
library(purrr)
library(glue)
plist <- map(
c(2, 5, 10, 20),
~ ggplot(mtcars, aes(disp, mpg)) +
geom_point() +
stat_smooth_draws(
times = .x, # this line specifies the number of draws
aes(group = stat(.draw)), size = 0.5
) +
annotate(
"label", x = Inf, y = Inf, hjust = 1, vjust = 1,
label = glue("{.x} draws", size = 12/.pt)
) +
theme_bw()
)
cowplot::plot_grid(plotlist = plist)
Example04 of ungeviz
总结
今天介绍的R语言ungeviz包在绘制一些常见的统计图形时非常有用,特别是涉及多组数据的一些统计指标的绘制时,可以完美替代ggplot2包中的stat_summary()类函数。喜欢的同学可以安装使用一下~~