【发布时间】:2018-02-04 18:53:21
【问题描述】:
我正在制作一个链接图(类似于 Carson Sievert 的 The SharedData plot pipeline 在 plotly for R 中。该图显示了我目前悬停在的一个项目的图例。但是,现在图例显示了两个元素,一个用于条形图和折线图。
- 如何删除第一个图例元素(条形图的红色方块)并只保留折线图的图例(红线)?
这是当前代码:
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
有人提到,最终删除图例元素可能会起作用,但在这里对我不起作用。
gp$x$data[[1]]$showlegend <- FALSE
【问题讨论】:
-
据我所知,您不能直接在 Plotly 中执行此操作。但是,您可以将 Javascript 代码添加到您的绘图中以处理您需要的内容。
标签: r plot charts legend plotly