在R绘图子图中,如何仅显示一个图例? [英] In R plotly subplot graph, how to show only one legend?

查看:716
本文介绍了在R绘图子图中,如何仅显示一个图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个图形的基本子图,默认情况下都具有图例,但是我只想看到其中一个.

I have a basic subplot with two graphs, both have a legend by default, but I want to see only one of them.

我尝试过这个:

require(plotly)
p1 <- plot_ly(data=iris,x=~Sepal.Length,y=~Sepal.Width,split=~Species) %>% layout(showlegend = FALSE)
p2 <-  plot_ly(data=iris,x=~Sepal.Length,y=~Sepal.Width,split=~Species) %>% layout(showlegend = TRUE)
subplot(p1,p2)
subplot(p2,p1)

但是它不起作用:好像只处理了一个showlegend属性,所以如果我从p1开始,我有两个图例,如果我从p2开始,我有两个图例.

But it doesn't work : it seems as if only one showlegend attribute was handled, so if I start with p1 I have two legend, if I start with p2 I have two.

有什么想法吗?

推荐答案

以上答案导致了一个小问题.图例仅与第一个情节互动.您需要将图例组添加到plot_ly函数中,以使图例与两个图交互.

The above answer results in a minor problem. The legend is only interactive with the first plot. You need to add the legendgroup to the plot_ly function to make the legend interactive with both plots.

library(plotly)
p1 <-
  iris%>%
  group_by(Species)%>%
  plot_ly(x=~Sepal.Length, color= ~Species, legendgroup=~Species)%>%
  add_markers(y= ~Sepal.Width)
p2 <-
  iris%>%
  group_by(Species)%>%
  plot_ly(x=~Sepal.Length, color= ~Species, legendgroup=~Species)%>%
  add_markers(y= ~Sepal.Width, showlegend=F)
subplot(p1,p2)

这篇关于在R绘图子图中,如何仅显示一个图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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