R plotly:在用ggplotly转换ggplot2时保留TWO图例的外观

时间:2017-03-15 21:16:14

标签: r ggplot2 plotly

我注意到,在使用ggplot2函数将plotly绘图转换为交互式ggplotly绘图时,可能会出现strange things

我正在绘制一个“Punchcard情节”,这是一种呈现数据集4维的好方法:

df <- data.frame(cat1 = rep(c("a","b","c"), 3), cat2 = c(rep("A", 3),
    rep("B", 3), rep("C", 3)), var1 = 1:9, var2 = 10:18)
ggplot(df, aes(x=cat1, y=cat2, size= var1, fill = var2)) +
    geom_point(shape=21)

enter image description here

但是,当我使用ggplotly转换为互动时,plotly只提供了一个传说:

p <- ggplot(df, aes(x=cat1, y=cat2, size= var1, fill = var2)) +
    geom_point(shape=21)
ggplotly(p)

enter image description here

  1. 为什么plotly会这样做,我该如何避免这种行为?

  2. 看到我遇到越来越多这些奇怪的事情 - 任何人都有链接到某个地方我可以阅读ggplotly如何运作,以某种方式我将来可以解决这些问题?

1 个答案:

答案 0 :(得分:5)

第二个传奇在转换过程中迷失了(或者至少我在数据中找不到)。您可以查看ggplotly的结果并修改从原始数据到布局的所有内容,例如gp[['x']][['layout']]将包含从ggplotly传递的所有布局变量。

enter image description here

更多代码行,但您可以完全控制图表的所有方面。

library(plotly)
df <- data.frame(cat1 = rep(c("a","b","c"), 3), 
                 cat2 = c(rep("A", 3),
                          rep("B", 3), 
                          rep("C", 3)), 
                 var1 = 1:9, 
                 var2 = 10:18)

size_multi <- 2 #multiplies your size to avoid pixel sized objects
color_scale <- list(c(0, "#000000"), list(1, "#00BFFF")) 
p <- plot_ly(df, 
              type='scatter', 
              mode='markers', 
              x = ~cat1, 
              y = ~cat2, 
              marker = list(color = ~var2, 
                            size=~var1 * size_multi,
                            colorscale = color_scale,
                            colorbar = list(len = 0.8, y = 0.3),
                            line = list(color = ~var2,
                                        colorscale = color_scale,
                                        width = 2)
                            ), 
              showlegend = F)



#adds some dummy traces for the punch card markers
markers = c(min(df$var1), mean(df$var1), max(df$var1))
for (i in 1:3) {
  p <- add_trace(p, 
                 df, 
                 type = 'scatter', 
                 mode = 'markers', 
                 showlegend = T, 
                 name = markers[[i]], 
                 x = 'x', 
                 y = 'x', 
                 marker = list(size = markers[[i]] * size_multi, 
                               color='rgba(255,255,255,0)',
                               showscale = F,
                               line = list(color = 'rgba(0,0,0,1)',
                                           width = 2))
                 )
}

#fix the coordinate system
spacer <- 0.2
p <- layout(p, xaxis=list(range=c(-spacer, length(levels(df$cat1)) - 1 + spacer)), yaxis=list(range=c(-spacer, length(levels(df$cat1)) - 1 + spacer)))
p