[英]How to draw transparent lines in ggplot2
I want to hide elements in my ggplot2 facets depending on a given variable. 我想根据给定的变量在ggplot2方面隐藏元素。 My first idea was to just switch those elements transparent, but they do not completely disappear from the plot (see image below).
我的第一个想法是将这些元素透明地切换,但是它们并没有完全从图中消失(请参见下图)。
For a label value less than 1 I dont want to plot the segment and the text. 对于小于1的标签值,我不想绘制段和文本。
library(tidyverse)
library(ggplot2)
carData <- mtcars
# get the max for each gear facet
df2 <- carData %>% group_by(gear) %>%
summarise(ypos = max(mpg)*1.1) %>%
mutate(x = 1, xend = 2) # use your factor level locators
df2$trans <- c(0,0,1)
df2$label <- c(0.1,0.1,3)
carData$cyl <- factor(carData$cyl)
p <- ggplot(carData, aes(cyl, mpg)) +
geom_boxplot() +
geom_segment(data = df2, aes(y = ypos, yend = ypos, x = x, xend = xend,alpha=trans)) +
geom_text(data = df2, aes(y = ypos*1.02, x = mean(c(x, xend)),label=label,alpha=trans))+
facet_wrap( ~ gear,ncol=2, scales="free")
p
Here is another solution for you: 这是为您提供的另一种解决方案:
p <- ggplot(carData, aes(cyl, mpg)) +
geom_boxplot() +
geom_segment(data = subset(df2,label > 1), aes(y = ypos, yend = ypos, x = x, xend = xend,alpha=trans)) +
geom_text(data = subset(df2,label > 1), aes(y = ypos*1.02, x = mean(c(x, xend)),label=label,alpha=trans))+
facet_wrap( ~ gear,ncol=2, scales="free")
p
You just need to subset the data in geom_segment
and geom_text
directly, such as for example: 您只需要直接对
geom_segment
和geom_text
的数据进行子集化,例如:
+ geom_segment(data = subset(df2,label > 1)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.