r - ggplot alpha = 0 不工作

标签 r ggplot2

我试图通过调整 alpha 值来复制一些纵向数据的轨迹图,并突出显示随机主题轨迹。我已经完成了 95% 的工作,除了当 alpha = 0 时我似乎无法获得线图的完全透明度(它仍然显示为灰色)。有任何想法吗? - 数据在这里:

https://d.pr/f/iIoE8q+

谢谢你。

# Assign random alpha (0 [90%] or 1 [10%]) values
macs <-  ddply(macs, .(id), function(x){
  x$alpha = ifelse(runif(n = 1) > 0.9, 1, 0)
  x
})

# Loess fit
fit <- loess(CD4 ~ time, data=macs, span = 0.5)

# Plot
ggplot(data = macs, aes(x = fitted(fit), y = resid(fit))) +
  geom_point(aes(alpha=1), size = 0.5) +  
  geom_line(aes(alpha=alpha, group=id)) + 
  guides(alpha=FALSE)

plot to replicate

my attempt

最佳答案

如果您尝试重现第一个图表,x 轴应该是时间,y 轴是拟合的残差。所以需要合并原始数据macs ,包含 time ,残差在 fit .我会用 broom::augment为了那个原因。

对于 alpha 问题,您需要将值转换为因子,然后使用 scale_alpha_discrete .

library(tidyverse)
library(broom)

fit %>% 
  augment() %>% 
  bind_cols(macs) %>% 
  mutate(alpha = factor(alpha)) %>%
  ggplot(aes(time, .resid)) + 
    geom_line(aes(group = id, alpha = alpha)) + 
    scale_alpha_discrete(range = c(0, 1)) + 
    geom_point(size = 0.5) + 
    guides(alpha = FALSE) + 
    theme_bw()

enter image description here

关于r - ggplot alpha = 0 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49247417/

相关文章:

r - 无需绘图即可扩展轴范围(以便按 x 单位对齐两个图)

r - 离散与连续情况下的映射与设置颜色

r - ggplot 中图例的自定义分组

r - 在 R 中的 ggplot2 中一起使用 stat_function 和 facet_wrap

r - GNU R : How to remove repeated characters at the beginning and end of every word of a string?

r - 我是按原样保留具有数字类别的特征还是创建虚拟变量?

R 用不同的名称保存多个文件

r - 将 gridExtra::grid.arrange 的输出存储到一个对象中

r - 将数据帧列拆分为分位数,对于 R 中的任何值都没有重复的分位数

r - 具有特征 "remove all-at-once"的 Shiny selectizeInput