我用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)

r - 在ggplotly中刻面时出现重复的图例-LMLPHP
?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日
r - 在ggplotly中刻面时出现重复的图例-LMLPHP
由于geom_bar的ggplotly错误,该错误会扭曲小节的数据,因此可能没有很好的方法。对于这种特殊情况,不需要刻面。您可以使用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)
r - 在ggplotly中刻面时出现重复的图例-LMLPHP
使用Plotly subplot()
如果必须使用此图类型,则可以使用Plotly的子图来构建类似小平面的图。不好看
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")))
r - 在ggplotly中刻面时出现重复的图例-LMLPHP

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

10-12 13:58