ggplot2展示图中部分数据的小例子
2021-04-29 本文已影响0人
R语言数据分析指南
有时我们进行绘图的时候,只想展示一部分内容这时该如何操作,ggplot2里面当然有相应的语法,但是如果有R包能完成此工作岂不更好,gghighlight包的出现很好的解决了这一问题,感谢Hiroaki Yutani开发出如此好用的R包

下面通过几个小例子来介绍如何使用
安装
install.packages("gghighlight")
# install.packages("devtools")
devtools::install_github("yutannihilation/gghighlight")
加载R包
library(tidyverse)
library(gghighlight)
构建数据
d <- purrr::map_dfr(
letters,
~ data.frame(
idx = 1:400,
value = cumsum(runif(400, -1, 1)),
type = .,
flag = sample(c(TRUE, FALSE), size = 400, replace = TRUE),
stringsAsFactors = FALSE
)
)
ggplot(d) +
geom_line(aes(idx, value, colour = type))+
theme_minimal()

ggplot(d) +
geom_line(aes(idx, value, colour = type)) +
gghighlight(max(value) > 12)

ggplot(d) +
geom_line(aes(idx, value, colour = type)) +
gghighlight(max(value) > 12) +
theme_minimal() +
facet_wrap(~ type)

p <- ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +
geom_point(size=4)
p

p + gghighlight(cyl == 6)

p + gghighlight(cyl == 6, keep_scales = TRUE) +
ggtitle("keep_scales = TRUE")

d2 <- dplyr::sample_n(d, 20)
ggplot(d2, aes(idx, value)) +
geom_point() +
gghighlight(value > 0, label_key = type)

d <- data.frame(
idx = c(1, 2, 3, 4, 1, 2, 3, 4),
value = c(10, 11, 12, 13, 4, 8, 16, 32),
cat1 = rep(c("a", "b"), each = 4),
cat2 = rep(rep(c("1-2", "3-4"), each = 2), 2),
stringsAsFactors = FALSE
)
p <- ggplot(d, aes(idx, value, colour = cat1)) +
geom_line() +
facet_wrap(vars(cat2))
p

p + gghighlight(max(value) > 10)

p +
gghighlight(max(value) > 10, calculate_per_facet = TRUE) +
ggtitle("calculate_per_facet = TRUE")

p <- ggplot(iris, aes(Sepal.Length, fill = Species)) +
geom_bar()+
gghighlight()
p

p + facet_wrap(~ Species)

set.seed(10)
d2 <- dplyr::sample_n(d, 20)
ggplot(d2, aes(idx, value)) +
geom_point() +
gghighlight(value > 0, label_key = type)