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

时间:2016-11-04 04:09:18

标签: 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")

我可以将鼠标悬停在每个矩形上,并为我指示数据的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 个答案:

答案 0 :(得分:4)

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

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

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

相关问题