R 使用plotly过滤链接视图中的图例
我正在绘制一个链接图(类似于R的plotly中的Carson Sievert)。该图显示了我当前悬停的一个项目的图例。但是,现在图例显示了两个元素,一个用于条形图,一个用于折线图R 使用plotly过滤链接视图中的图例,r,plot,charts,legend,plotly,R,Plot,Charts,Legend,Plotly,我正在绘制一个链接图(类似于R的plotly中的Carson Sievert)。该图显示了我当前悬停的一个项目的图例。但是,现在图例显示了两个元素,一个用于条形图,一个用于折线图 如何删除第一个图例元素(条形图的红色方框),并仅保留折线图的图例(红线) 以下是当前代码: library(ggplot2) library(crosstalk) library(plotly) sd <- SharedData$new(txhousing, ~city) base <- plot_
- 如何删除第一个图例元素(条形图的红色方框),并仅保留折线图的图例(红线)
library(ggplot2)
library(crosstalk)
library(plotly)
sd <- SharedData$new(txhousing, ~city)
base <- plot_ly(sd, color = I("black")) %>%
group_by(city) %>%
layout(showlegend = TRUE)
p1 <- base %>%
summarise(has = sum(is.na(median))) %>%
filter(has > 0) %>%
arrange(has) %>%
add_bars(x = ~has, y = ~factor(city, levels = city),
hoverinfo = "none", showlegend = FALSE) %>%
layout(
barmode = "overlay",
xaxis = list(title = "Number of months missing"),
yaxis = list(title = "")
)
p2 <- base %>%
add_lines(x = ~date, y = ~median, alpha = 0.3, showlegend = FALSE) %>%
layout(xaxis = list(title = ""))
gp <- subplot(p1, p2, titleX = TRUE, widths = c(0.3, 0.7)) %>%
layout(margin = list(l = 120)) %>%
highlight(color = "red",
defaultValues = "Victoria",
selected = attrs_selected(showlegend = TRUE, mode = "lines"
))
gp
库(ggplot2)
图书馆(串扰)
图书馆(绘本)
sd%
布局(showlegend=TRUE)
p1%
总结(has=总和(is.na(中位数))%>%
筛选器(已>0)%>%
安排(has)%>%
添加_条(x=~ has,y=~因子(city,levels=city),
hoverinfo=“无”,showlegend=FALSE)%>%
布局(
barmode=“覆盖”,
xaxis=列表(title=“缺少的月数”),
yaxis=列表(title=”“)
)
p2%
添加_行(x=~日期,y=~中值,alpha=0.3,showlegend=FALSE)%>%
布局(xaxis=列表(title=”“))
gp%
布局(边距=列表(l=120))%>%
突出显示(color=“red”,
defaultValues=“维多利亚”,
已选择=属性已选择(showlegend=TRUE,mode=“lines”
))
全科医生
有人在某处提到,最终删除legend元素可能会起作用,但在这里对我不起作用
gp$x$data[[1]]$showlegend <- FALSE
gp$x$data[[1]]$showlegend如果Plotly没有为我们提供隐藏由高亮显示创建的图例的方法,那么让我们使用Plotly自己的函数来实现
一次隐藏跟踪所需的Javascript代码:
var updated = {showlegend: false};
var myPlot = document.getElementsByClassName('plotly')[0];
Plotly.restyle(myPlot, updated, [2]);
在这种情况下,需要隐藏图例的总是第三个元素[2]
,通常最好根据某些条件动态获取索引
让我们将此添加到Plotly的单击事件上的,以确保该图例将来也不可见
myPlot.on('plotly_click', function(data){
Plotly.restyle(myPlot, updated, [2]);
});
最后把所有的东西都加到输出中,我们就好了
javascript <- "
var updated = {showlegend: false};
var myPlot = document.getElementsByClassName('plotly')[0];
Plotly.restyle(myPlot, updated, [2]);
myPlot.on('plotly_click', function(data){
Plotly.restyle(myPlot, updated, [2]);
});
"
w <- plotly::as_widget(gp)
w <- htmlwidgets::prependContent(w, onStaticRenderComplete(javascript), data=list(''))
htmlwidgets::saveWidget(w, "cities.html")
w
javascript据我所知,您不能直接在Plotly中执行此操作。但是,您可以将javascript代码添加到绘图中,以满足您的需要。