问题描述
我在 r
中使用 plotly
来生成许多子图.下面显示了一个玩具示例.
I'm using plotly
in r
to generate a number of subplots. A toy example is shown below.
library(shiny)
library(dplyr)
library(plotly)
## Toy Example
ui <- fluidPage(
h3("Diamonds"),
plotlyOutput("plot", height = 600)
)
server <- function(input, output, session) {
# reduce down the dataset to make the example simpler
dat <- diamonds %>%
filter(clarity %in% c("I1", "IF")) %>%
mutate(clarity = factor(clarity, levels = c("I1", "IF")))
output$plot <- renderPlotly({
# Generates the chart for a single clarity
byClarity <- function(df){
Clarity <- df$clarity[1];
plot_ly(df, x = ~carat, y = ~price, color = ~cut, name = ~clarity) %>%
add_trace(
type="bar"
## Also tried adding this with no success
# legendgroup = ~cut
) %>%
layout(
barmode = "stack"
)
}
dat %>%
split(.$clarity) %>%
lapply(byClarity) %>%
subplot(nrows = NROW(.), shareX = TRUE, which_layout = "merge")
})
}
shinyApp(ui, server)
我想制作图例,以便单击图例上的剪切"将显示/隐藏 两个图表中的剪切",而不仅仅是与该图例关联的图表.
I would like to make the legends such that clicking on a 'Cut' on the legend will show/hide that 'Cut' from both charts instead of just the chart associated with that legend.
我查看了 legendgroup,但不知道如何将它与 cut
而不是 clarity
关联(clarity
是我的分组m 用于制作子图).
I looked at legendgroup but can't figure out how to associate it with cut
instead of clarity
(clarity
is the grouping I'm using to make the subplots).
我还需要使用原始 plot_ly
而不是 ggplotly
的解决方案,因为我还需要其他 plot_ly
功能'在 ggplotly
中不可用.
I also need the solution to work with raw plot_ly
and not ggplotly
as there are other plot_ly
functionalities I need that aren't available in ggplotly
.
任何帮助将不胜感激.我正在使用 plotly_4.5.2
、dplyr_0.5.0
和 shiny_0.14
.
Any help would be appreciated. I am using plotly_4.5.2
, dplyr_0.5.0
, and shiny_0.14
.
推荐答案
好的,下面是使用ggplot2
的解决方案:
Ok, here is a solution using ggplot2
:
library(ggplot2)
library(dplyr)
library(plotly)
dat <- diamonds %>%
filter(clarity %in% c("I1", "IF")) %>%
mutate(clarity = factor(clarity, levels = c("I1", "IF")))
# Function for nice labels
k_label <- function(x) {
c(0, paste0((x)/1000,"K")[-1])
}
# ggplot
p <- ggplot(dat,aes(x=carat, y=price, fill=cut)) +
geom_bar(stat="identity") +
facet_wrap(~clarity,nrow=2, scales = "free_y") +
scale_y_continuous(labels = k_label) +
theme_minimal() + ylab("") + xlab("") +
theme(legend.title=element_blank(),
panel.grid.major.x=element_blank())
# a plotly
ggplotly(p)
这篇关于为子图绘制图例组,因此单个图例控制所有图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!