r - 使用 facet_wrap 从 ggplot 进行绘图转换时避免图例重复

标签 r ggplot2 plotly r-plotly

考虑由以下 reprex 生成的图。请注意,ggplot 具有合理的图例,而在 plotly 中,图例被大量重复,每次相同类别(“制造商”)出现在每个方面时都有一个条目。如何使 plotly 图例更好地匹配 ggplot2 的图例?

library(plotly)
library(ggplot2)

p <- mpg %>% 
  ggplot(aes(year)) +
  geom_ribbon(aes(ymin=cty, ymax=hwy, fill = manufacturer), alpha=0.2) + 
  geom_line(aes(y = hwy, col=manufacturer))  +
  facet_wrap(~class)
p
ggplot
plotly::ggplotly(p)
plotly

最佳答案

调整我对 this 的回答发布到您的案例(利用此 answer )一种选择是操纵 plotly目的。
问题是,对于刻面,我们最终会为存在组的每个刻面生成一个图例条目,即图例条目中的数字对应于刻面或面板的编号。
plotly可以通过 legendgroup 防止重复的图例条目争论。使用 ggplotly 时获得相同结果的一种选择将分配 legendgroup像这样手动:

library(plotly)
library(ggplot2)

p <- mpg %>% 
  ggplot(aes(year)) +
  geom_ribbon(aes(ymin=cty, ymax=hwy, fill = manufacturer), alpha=0.2) + 
  geom_line(aes(y = hwy, col=manufacturer))  +
  facet_wrap(~class)

gp <- ggplotly(p = p)

# Get the names of the legend entries
df <- data.frame(id = seq_along(gp$x$data), legend_entries = unlist(lapply(gp$x$data, `[[`, "name")))
# Extract the group identifier
df$legend_group <- gsub("^\\((.*?),\\d+\\)", "\\1", df$legend_entries)
# Add an indicator for the first entry per group
df$is_first <- !duplicated(df$legend_group)

for (i in df$id) {
  # Is the layer the first entry of the group?
  is_first <- df$is_first[[i]]
  # Assign the group identifier to the name and legendgroup arguments
  gp$x$data[[i]]$name <- df$legend_group[[i]]
  gp$x$data[[i]]$legendgroup <- gp$x$data[[i]]$name
  # Show the legend only for the first layer of the group 
  if (!is_first) gp$x$data[[i]]$showlegend <- FALSE
}
gp

关于r - 使用 facet_wrap 从 ggplot 进行绘图转换时避免图例重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69289623/

相关文章:

r - plotly -R : specifying size of marker in add_trace() reduces opacity of markers

r - 成对相关表

r - R中约束优化的非单调输出

r - 尝试在 ggplot2 中创建多面图时出错

r - 计算最大直方图值

python - plotly 桑基 : why are nodes misplaced?

r - 无法从打印的html文件中查看gvisMotionChart

r - 通过 magrittr 传递命名参数

r - 几何平滑: what is its meaning (why is it lower than the mean?)

r - 使用plotly绘制多个ggplot2图