2016-11-04 68 views
0

我想创建一个交互式阴谋用长方形使用情节在R.保持geom_rect半透明区域,但彩色的轮廓

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

下面是什么工作的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") 

我可以在每个矩形徘徊,并有向我表示的数据的名称变量。而且,数据的填充变量决定矩形的颜色。但是,我无法使矩形变得透明。

我尝试:

1)改变填充= NULL填充= NA,但是这将导致误差:

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

2)改变的α= 0.5于α= 0.01,但是这使得每个矩形的轮廓也相当透明。

只有矩形区域完全透明才能创建这种类型的图形?我真的希望保持矩形的轮廓颜色,并能够响应不同的alpha值。

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

+1

也许'geom_rect(...,补= NA)这样做' – cuttlefish44

+1

确保你已经做了在'geom_rect'中'fill = NA' *'aes'的外*,如@ cuttlefish44评论所示。 – aosmith

回答

0

其实很简单。对于填充参数,只需使用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