r - 如何使用 plotly subplots() 删除重复的图例条目
问题描述
使用 plotly 的 subplots() 时如何删除图例中的重复项?
这是我的 MWE:
library(plotly)
library(ggplot2)
library(tidyr)
mpg %>%
group_by(class) %>%
do(p = plot_ly(., x = ~cyl, y = ~displ, color = ~trans, type = 'bar')) %>%
subplot(nrows = 2, shareX = TRUE, titleX = TRUE) %>%
layout(barmode = 'stack')
解决方案
plotly
没有facet
喜欢ggplot2
,所以它会为每个添加图例,subplot
或者您可以为其中一些关闭它。
在这里,我们没有包含所有~class
条目的层,也没有两个没有交集的图,class
其中它们的组合也覆盖了所有条目。在这种情况下,我们可以为那些特定的情节设置为,并将其设置showlegend
为其余部分,并将其设置为,以便我们获得一个独特但完整的图例。TRUE
FALSE
legendgroup
trans
正如我所说,这里我们没有那种特殊情况。所以我能想到的有两种可能:
添加整个数据(复制整个数据框)并
All
为它们分配类。然后将其与原始数据一起绘制,但仅将图例保留为class == All
.使用
ggplot::facet_wrap
and thenggplotly
来制作一个plotly
对象。但是,这会导致一些问题x-axis
(将对象与ggplot
对象进行plotly
比较)。
library(plotly)
library(ggplot2)
library(dplyr)
ly_plot <- . %>%
plot_ly(x = ~cyl, y = ~displ, color = ~trans,
type = 'bar', showlegend = ~all(legendC)) %>%
add_annotations(
text = ~unique(class),
x = 0.5,
y = 1,
yref = "paper",
xref = "paper",
xanchor = "middle",
yanchor = "top",
showarrow = FALSE,
font = list(size = 15))
mpg %>%
mutate(class= "_All_") %>%
rbind(.,mpg) %>%
mutate(legendC = (class == "_All_")) %>%
group_by(class) %>%
do(p = ly_plot(.)) %>%
subplot(nrows = 2, shareX = TRUE, titleX = TRUE) %>%
layout(barmode = 'stack')
#> Warning in RColorBrewer::brewer.pal(N, "Set2"): n too large,
#> allowed maximum for palette Set2 is 8
#> Returning the palette you asked for with that many colors
p <- ggplot(data = mpg, aes(x=cyl, y=displ, fill=trans))+
geom_bar(stat="identity") +
facet_wrap(~class)
p
ggplotly(p) #seems for this we should also set "colour = trans"
推荐阅读
- c# - 如何在 ASP.NET Core 2.2 中监听输出日志
- xamarin.forms - 为什么 SkiaSharp 'OnCanvasView_PaintSurface' 不会在 Xamarin.Form 应用程序中自动重新绘制
- c# - Application.ActiveWindow.Selection.ShapeRange 未选择任何内容时抛出异常
- javascript - 用于绘制 Visual Studio 图表的 XML 数据
- python - 运行 fit_generator 时无法理解“IndexError: tuple index out of range”的原因
- python - 有没有办法将 python 依赖项添加到柯南包
- laravel - 在服务器端或前端分页更好吗?
- jsfl - jsfl:访问符号以在其中设置动画
- java - 地图中的 Java 枚举使用
- javascript - 如何在 TensorFlow.js 中将 optimizer.minimize 与 maxPooling 层一起使用