簡體   English   中英

如何在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_segmentgeom_text的數據進行子集化,例如:

+ geom_segment(data = subset(df2,label > 1)...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM