如何在ggplot2中绘制透明线
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
你快到了。只需要覆盖 alpha 比例的默认范围,即 c(0.1, 1)
:
p + scale_alpha(range = c(0, 1))
这里有另一个解决方案:
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)...
我想根据给定的变量隐藏我的 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
你快到了。只需要覆盖 alpha 比例的默认范围,即 c(0.1, 1)
:
p + scale_alpha(range = c(0, 1))
这里有另一个解决方案:
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)...