ggplot2扩展功能包:ggpmisc和gginnards

2021-06-01 16:29:04 浏览数 (1)

ggpmisc和gginnards两个包包含了ggplot2很多扩展的功能。

介绍其中几个实用函数。

代码语言:javascript复制
#install.packages("gginnards")
#install.packages("ggpmisc")

library(gginnards)
library(ggpmisc)

stat_poly_eq

可以直接获得曲线拟合的方程,p值,决定系数(R^2), AIC和BIC等指标,不需要自己计算和标注了。不过只能做多项式拟合lm()的结果。

代码语言:javascript复制
##例子
# generate artificial data
set.seed(4321)
x <- 1:100
y <- (x   x^2   x^3)   rnorm(length(x), mean = 0, sd = mean(x^3) / 4)
my.data <- data.frame(x = x, y = y,
                      group = c("A", "B"),
                      y2 = y * c(0.5,2),
                      w = sqrt(x))

# give a name to a formula
formula <- y ~ poly(x, 3, raw = TRUE)

# user specified label
ggplot(my.data, aes(x, y))  
  geom_point()  
  geom_smooth(method = "lm", formula = formula)  
  stat_poly_eq(aes(label =  paste(stat(eq.label),
                                  stat(adj.rr.label),
                                  stat(p.value.label),
                                  sep = "*", "*")),
               formula = formula, 
               rr.digits = 3, coef.digits = 4,
               parse = TRUE)

geom_linked_text

花式加标签

代码语言:javascript复制
##例子
my.cars <- mtcars[c(TRUE, FALSE, FALSE, FALSE), ]
my.cars$name <- rownames(my.cars)
p <- ggplot(my.cars, aes(wt, mpg, label = name))

p  
  geom_point()  
  geom_linked_text(aes(colour = factor(cyl)),
                   hjust = -0.04, nudge_x = 0.12,
                   vjust = -0.2, nudge_y = 0.5,
                   size = 4,
                   check_overlap = TRUE, # avoid overlap
                   arrow = arrow(length = grid::unit(1.5, "mm")))  
  expand_limits(x = 6.2)

geom_table

插入表格

代码语言:javascript复制
##例子
library(dplyr)
library(tibble)

mtcars %>%
  group_by(cyl) %>%
  summarize(wt = mean(wt), mpg = mean(mpg)) %>%
  ungroup() %>%
  mutate(wt = sprintf("%.2f", wt),
         mpg = sprintf("%.1f", mpg)) -> tb

df <- tibble(x = 5.45, y = 34, tb = list(tb))

ggplot(mtcars, aes(wt, mpg, colour = factor(cyl)))  
  geom_point()  
  geom_table(data = df, aes(x = x, y = y, label = tb),
             table.rownames = TRUE, table.theme = ttheme_gtstripes)

stat_fit_tb

对多种模型进行拟合并返回拟合结果; 对拟合结果做ANOVA

代码语言:javascript复制
library(broom)

# data for examples
x <- c(44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1)
covariate <- sqrt(x)   rnorm(9)
group <- factor(c(rep("A", 4), rep("B", 5)))
my.df <- data.frame(x, group, covariate)

# Linear regression fit summary, by default
ggplot(my.df, aes(covariate, x))  
  geom_point()  
  stat_fit_tb(digits = 2, p.digits = 4)  
  expand_limits(y = 70)

其他还有很多功能,自行探索吧~

0 人点赞