有时我们进行绘图的时候,只想展示一部分内容这时该如何操作,ggplot2里面当然有相应的语法,但是如果有R包能完成此工作岂不更好,gghighlight包的出现很好的解决了这一问题,感谢Hiroaki Yutani开发出如此好用的R包
![](https://img.haomeiwen.com/i16360488/b697ebc81c286539.jpg)
下面通过几个小例子来介绍如何使用
安装
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()
![](https://img.haomeiwen.com/i16360488/f6077bbfd374ace4.png)
ggplot(d) +
geom_line(aes(idx, value, colour = type)) +
gghighlight(max(value) > 12)
![](https://img.haomeiwen.com/i16360488/a65a3b3588582723.png)
ggplot(d) +
geom_line(aes(idx, value, colour = type)) +
gghighlight(max(value) > 12) +
theme_minimal() +
facet_wrap(~ type)
![](https://img.haomeiwen.com/i16360488/2e2e2cf74b1b0247.png)
p <- ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +
geom_point(size=4)
p
![](https://img.haomeiwen.com/i16360488/c866ee56c0cc4b39.png)
p + gghighlight(cyl == 6)
![](https://img.haomeiwen.com/i16360488/1a8696af8ce0848e.png)
p + gghighlight(cyl == 6, keep_scales = TRUE) +
ggtitle("keep_scales = TRUE")
![](https://img.haomeiwen.com/i16360488/4e6aa9326e579561.png)
d2 <- dplyr::sample_n(d, 20)
ggplot(d2, aes(idx, value)) +
geom_point() +
gghighlight(value > 0, label_key = type)
![](https://img.haomeiwen.com/i16360488/31d4181cc13f3901.png)
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
![](https://img.haomeiwen.com/i16360488/0fe3e0de1a732683.png)
p + gghighlight(max(value) > 10)
![](https://img.haomeiwen.com/i16360488/4a600d1a2adf5a31.png)
p +
gghighlight(max(value) > 10, calculate_per_facet = TRUE) +
ggtitle("calculate_per_facet = TRUE")
![](https://img.haomeiwen.com/i16360488/8b25d4f19b4ae7a0.png)
p <- ggplot(iris, aes(Sepal.Length, fill = Species)) +
geom_bar()+
gghighlight()
p
![](https://img.haomeiwen.com/i16360488/6a1e147d64071e40.png)
p + facet_wrap(~ Species)
![](https://img.haomeiwen.com/i16360488/c361a4b797100cd0.png)
set.seed(10)
d2 <- dplyr::sample_n(d, 20)
ggplot(d2, aes(idx, value)) +
geom_point() +
gghighlight(value > 0, label_key = type)
网友评论