r - 在 ggplotly 中分面时出现重复的图例

标签 r ggplot2 plotly

我正在用 ggplotly() 制作一些数字并注意到 facet_wrapfacet_grid导致图例中的每个项目按面数重复。有没有办法阻止这种情况?

例如:

library("ggplot2")
library("plotly")
diamonds = diamonds[diamonds$cut %in% c("Fair", "Good"),]
dia = ggplot(diamonds, aes(x = cut)) + 
  geom_bar(aes(stat = "identity", fill = cut)) + 
  facet_grid(.~color)

ggplotly(dia)

enter image description here
?plotly文档不是很详细,也没有these有传说。

这是我输入 ggplotly 时出现的结果如果这给出了任何见解:
function (p = ggplot2::last_plot(), filename, fileopt, world_readable = TRUE) 
{
    l <- gg2list(p)
    if (!missing(filename)) 
        l$filename <- filename
    if (!missing(fileopt)) 
        l$fileopt <- fileopt
    l$world_readable <- world_readable
    hash_plot(p$data, l)
}

最佳答案

更新
问题似乎已在 Plotly 3.6.0 中得到修复——2016 年 5 月 16 日
enter image description here
由于 geom_bar 的 ggplotly 错误会扭曲条形图的数据,因此可能没有好的方法可以做到这一点。对于这种特殊情况,不需要 facet。您可以使用 plot_ly() 来构建有效的绘图。
plotly

require(plotly)
require(dplyr)

d <- diamonds[diamonds$cut %in% c("Fair", "Good"),] %>%
  count(cut, color)

plot_ly(d, x = color, y = n, type = "bar", group = cut)
enter image description here
使用 Plotly subplot()
如果必须使用这种绘图类型,您可以使用 Plotly 的子绘图构建一个类似 facet 的绘图。它不漂亮。
d2 <- diamonds[diamonds$cut %in% c("Fair", "Good"),] %>%
  count(cut, color) %>%
  transform(color = factor(color, levels=rev(levels(color)))) %>%
  mutate(id = as.integer(color)) 

p <- plot_ly(d2, x = cut, y = n, type = "bar", group = color, xaxis = paste0("x", id), marker = list(color = c("#0000FF","#FF0000"))) %>%
  layout(yaxis = list(range = range(n), linewidth = 0, showticklabels = F, showgrid = T, title = ""),
         xaxis = list(title = ""))

subplot(p) %>%
  layout(showlegend = F,
         margin = list(r = 100),
         yaxis = list(showticklabels = T),
         annotations = list(list(text = "Fair", showarrow = F, x = 1.1, y = 1, xref = "paper", yref = "paper"),
                            list(text = "Good", showarrow = F, x = 1.1, y = 0.96, xref = "paper", yref = "paper")),
         shapes = list(list(type = "rect", x0 = 1.1, x1 = 1.13, y0 = 1, y1 = 0.97, line = list(width = 0), fillcolor = "#0000FF", xref = "paper", yref = "paper"),
                       list(type = "rect", x0 = 1.1, x1 = 1.13, y0 = 0.96, y1 = 0.93, line = list(width = 0), fillcolor = "#FF0000", xref = "paper", yref = "paper")))
enter image description here

关于r - 在 ggplotly 中分面时出现重复的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34405700/

相关文章:

r - 查找两列中的重复项

r - ggplot2 在平淡的奥特曼图中为每个方面添加几何线

r - 是否有一个函数可以查找字符向量中的所有小写字母?

r - 使用 alpha 美学映射的 ggplot2 stat_summary_hex 示例?

r - 如何将字符对象添加到 ggplot2 : adding the % symbol to the percentage label in a bar chart 中的数字标签

python - pyinstaller 因 plotly 而失败

使用 dplyr 从另一列返回值

r - ggplot2 ggsave 函数导致图形设备不显示绘图

python-3.x - Docker 和 Plotly

r - 使用 plotly rstudio 从数据框创建漏斗图