考虑由以下 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
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
关于r - 使用 facet_wrap 从 ggplot 进行绘图转换时避免图例重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69289623/