防止ggplotly从图例中删除未使用的因子级别

时间:2017-04-28 15:47:17

标签: r ggplot2 plotly

我有这个数据框:

> dd
   x xend         y     yend group
7  1    1 -2.592981 2.531884     C
8  2    2 -3.052151 2.570183     A
9  3    3 -3.255346 2.663808     C
10 4    4 -3.456388 2.905152     A
> str(dd)
'data.frame':   4 obs. of  5 variables:
 $ x    : num  1 2 3 4
 $ xend : num  1 2 3 4
 $ y    : num  -2.59 -3.05 -3.26 -3.46
 $ yend : num  2.53 2.57 2.66 2.91
 $ group: Factor w/ 3 levels "A","B","C": 3 1 3 1

我想绘制一些由group因子着色的片段,而不会从图例中删除未使用的因子水平。像这样:

gg <- ggplot(dd, aes(x, y, color=group)) +
   scale_colour_discrete(drop = FALSE) +
   geom_segment(aes(xend=xend, yend=yend))

这可以按预期工作:

ggplot

但现在我想要一个plotly图形。并ggplotly删除未使用的级别:

ggplotly(gg)

enter image description here

有没有办法阻止ggplotly删除未使用的因子级别?

数据框:

> dput(dd)
structure(list(x = c(1, 2, 3, 4), xend = c(1, 2, 3, 4), y = c(-2.59298110869713, 
-3.05215109954588, -3.25534630590118, -3.45638777944259), yend = c(2.53188374522142, 
2.57018254452851, 2.66380767012015, 2.90515183040407), group = structure(c(3L, 
1L, 3L, 1L), .Label = c("A", "B", "C"), class = "factor")), .Names = c("x", 
"xend", "y", "yend", "group"), class = "data.frame", row.names = 7:10)

包版本:

> packageVersion("ggplot2")
[1] ‘2.2.1.9000’
> packageVersion("plotly")
[1] ‘4.6.0’

1 个答案:

答案 0 :(得分:1)

据我所知,没有直接的做法,但你添加了一个&#34;虚拟&#34;每个缺失group值的行,例如

for (diff in setdiff(levels(dd$group), unique(dd$group))) {
  dummy_name = paste0('dummy_', diff) 
  dd[dummy_name,] <- dd[1,]
  for (n in names(dd[1,])) {
    dd[dummy_name,][n] = NaN
  }
  dd[dummy_name,]$group <- diff
}

将提供以下数据框

          x xend         y     yend group
7         1    1 -2.592981 2.531884     C
8         2    2 -3.052151 2.570183     A
9         3    3 -3.255346 2.663808     C
10        4    4 -3.456388 2.905152     A
dummy_B NaN  NaN       NaN      NaN     B

以及以下情节

enter image description here

dd = structure(list(x = c(1, 2, 3, 4), 
                    xend = c(1, 2, 3, 4), 
                    y = c(-2.59298110869713, -3.05215109954588, -3.25534630590118, -3.45638777944259), 
                    yend = c(2.53188374522142, 2.57018254452851, 2.66380767012015, 2.90515183040407), 
                    group = structure(c(3L, 1L, 3L, 1L), 
                                      .Label = c("A", "B", "C"), 
                                      class = "factor")), 
               .Names = c("x", "xend", "y", "yend", "group"), 
               class = "data.frame", 
               row.names = 7:10)
for (diff in setdiff(levels(dd$group), unique(dd$group))) {
  dummy_name = paste0('dummy_', diff) 
  dd[dummy_name,] <- dd[1,]
  for (n in names(dd[1,])) {
    dd[dummy_name,][n] = NaN
  }
  dd[dummy_name,]$group <- diff
}

gg <- ggplot(dd, aes(x, y, color=group)) +
  scale_colour_discrete(drop = FALSE) +
  geom_segment(aes(xend=xend, yend=yend))

gg
ggplotly(ggplot(dd, aes(x, y, color=group)) +
           scale_colour_discrete(drop = FALSE) +
           geom_segment(aes(xend=xend, yend=yend)))