首页 文章

保持geom_rect半透明区域,但彩色轮廓

提问于
浏览
1

我试图在R中使用plotly创建一个带有矩形的交互式绘图 .

我的主要想法是工作 . 然而,我所坚持的是允许每个矩形具有彩色轮廓(如数据的“填充”列中所描绘的),但是完全透明的区域 .

以下是工作的MWE:

library(ggplot2)
library(dplyr)
library(plotly)
set.seed(1)
data <- data.frame(Name = paste0("Name",seq(1:10)), xmin = runif(10, 0, 1), xmax = runif(10, 1, 2), ymin = runif(10, 0, 1), ymax = runif(10, 1, 2), fill = sample(c("black","purple"),10, replace=TRUE) )

p <- ggplot(data, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = NULL, colour = fill, text = Name)) + geom_rect(size = 0.3, alpha = 0.5) + scale_colour_identity() + theme_bw()
ggplotly(p, tooltip = "text") %>% layout(dragmode = "select")

我可以将鼠标悬停在每个矩形上,并为我指示数据的Name变量 . 而且,数据的填充变量决定了矩形的颜色 . 但是,我无法使矩形透明 .

我试过了:

1)更改fill = NULL以填充= NA,但这会导致错误:

Error in seq.default(h[1], h[2], length.out = n) : 
  'to' cannot be NA, NaN or infinite

2)将alpha = 0.5更改为alpha = 0.01,但这使得每个矩形的轮廓也相当透明 .

是否可以仅在矩形区域完全透明的情况下创建此类绘图?我真的希望保持矩形的轮廓着色,并且能够响应不同的alpha值 .

如果您对我有任何建议,我会很高兴听到它!

1 回答

  • 2

    它实际上很简单 . 只需使用透明颜色为 geom_rect 函数使用 fill=alpha("grey",0) 填充参数,您将获得所需的结果 .

    您可以通过修改以下代码来实现

    p <- ggplot(data, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, colour = "purple", text = Name)) + geom_rect(size = 0.3, alpha = 0.5,fill=alpha("grey",0)) + scale_colour_identity() + theme_bw()
    ggplotly(p, tooltip = "text") %>% layout(dragmode = "select")
    

    输出看起来像
    Output Image

相关问题