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

1 r ggplot2 plotly

我正在尝试使用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")
Run Code Online (Sandbox Code Playgroud)

我可以将鼠标悬停在每个矩形上,并向我显示数据的Name变量。此外,数据的填充变量决定了矩形的颜色。但是,我无法使矩形透明。

我试过了:

1)将fill = NULL更改为fill = NA,但这会导致错误:

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

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

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

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

9He*_*ads 5

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

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

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")
Run Code Online (Sandbox Code Playgroud)

输出看起来像 输出图像