在ggplotly中进行分面时重复的图例

Nan*_*ncy 6 r ggplot2 plotly

我正在制作一些数字ggplotly()并注意到这一点,facet_wrap并facet_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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

该?plotly文件是不是很复杂的,而且没有任何这些具有传奇.

这就是我输入的内容,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)
}
Run Code Online (Sandbox Code Playgroud)

Van*_*pez 2

更新

Plotly 3.6.0 似乎已修复问题 - 2016 年 5 月 16 日 在此输入图像描述

由于 geom_bar 的 ggplotly 错误会扭曲条形图的数据,因此可能没有一个好的方法来做到这一点。对于这种特殊情况,不需要facet。您可以使用plot_ly()来构建有效的绘图。

情节_ly

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

使用 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")))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述