ggplot2扩展包:ggpp绘制图中图、图中表

2022-04-18 14:37:07 浏览数 (1)

包"ggpp"提供了一组构建块,用于扩展在包"ggplot2"中实现的图形语法(> = 3.0.0)。新的"geoms"支持在地块、边际标记和使用原生地块坐标(npc)中插入。位置函数实现了新的方法来轻推可用于任何几何图形,但与 和 一起特别有用。

参考:https://exts.ggplot2.tidyverse.org/gallery/

代码语言:javascript复制
if(!require(devtools)) install.packages("ggpp")
library(ggpp)
library(ggrepel)
library(dplyr)

# Insets A plot with an inset table.
# 图中插入表
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))
代码语言:javascript复制
# A plot with an inset plot.
# 图中插入图
p <- ggplot(mtcars, aes(factor(cyl), mpg, colour = factor(cyl)))  
  stat_boxplot()  
  labs(y = NULL, x = "Engine cylinders (number)")  
  theme_bw(9)   theme(legend.position = "none")

ggplot(mtcars, aes(wt, mpg, colour = factor(cyl)))  
  geom_point(show.legend = FALSE)  
  annotate("plot_npc", npcx = "left", npcy = "bottom", label = p)  
  expand_limits(y = 0, x = 0)
代码语言:javascript复制
# Medians computed on-the-fly displayed marginal arrows.
# 实时计算的中位数显示边缘箭头。
ggplot(mtcars, aes(wt, mpg, colour = factor(cyl)))  
  geom_point()  
  stat_centroid(geom = "y_margin_arrow", .fun = median,
                aes(yintercept = after_stat(y)), arrow.length = 0.05)
代码语言:javascript复制

# Nudging and stacking combined
# 堆积
df <- data.frame(x1 = c(1, 2, 1, 3, -1),
                 x2 = c("a", "a", "b", "b", "b"),
                 grp = c("some long name", "other name", "some name",
                         "another name", "a name"))

# Add labels to a horizontal column plot (stacked by default)
ggplot(data = df, aes(x2, x1, group = grp))  
  geom_col(aes(fill = grp), width=0.5)  
  geom_hline(yintercept = 0)  
  geom_text(
    aes(label = grp),
    position = position_stacknudge(vjust = 1, y = -0.2))  
  theme(legend.position = "none")

0 人点赞