[英]How to draw transparent lines in ggplot2
我想根據給定的變量在ggplot2方面隱藏元素。 我的第一個想法是將這些元素透明地切換,但是它們並沒有完全從圖中消失(請參見下圖)。
對於小於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
這是為您提供的另一種解決方案:
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
您只需要直接對geom_segment
和geom_text
的數據進行子集化,例如:
+ geom_segment(data = subset(df2,label > 1)...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.