使用Facet_WRAP从ggploy进行绘图转换时避免图例重复 [英] Avoid legend duplication in plotly conversion from ggplot with facet_wrap

查看:9
本文介绍了使用Facet_WRAP从ggploy进行绘图转换时避免图例重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑由以下表示法生成的情节。请注意,ggploy有合理的图例,而在Ploly中,图例被大量复制,每次相同的类别(制造商和制造商)出现在每个方面时,都有一个条目。如何使情节图例与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

plotly::ggplotly(p)

推荐答案

将我在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

这篇关于使用Facet_WRAP从ggploy进行绘图转换时避免图例重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆