【发布时间】:2021-07-02 07:15:10
【问题描述】:
MWE:
# Packages; ####
library(tidyverse)
library(plotly)
# Plot; #####
mtcars %>%
group_by(gear,am) %>%
summarise(
mpg = mean(mpg)
) %>% do(
plot = plot_ly(
data = .,
x = ~gear,
y = ~mpg
) %>% add_bars(
name = ~am
)
) %>% subplot(
nrows = 1,
shareY = TRUE,
shareX = TRUE
) %>% layout(
title = "Facetted Plot",
xaxis = list(title = "")
)
这个plot 有三个图例,每个gear 一个。如何动态地将所有 Xaxis 动态设置为"",而无需显式指定xaxis = list(title = "")、xaxis1 = list(title = "")?
我自己的半心半意的尝试/想法是像这样在function 中使用parse 和eval,
plot_function <- function(grouping_vars) {
# Baseplot; ####
base_plot = mtcars %>%
group_by(!!sym(grouping_vars[1]),!!sym(grouping_vars[2])) %>%
summarise(
mpg = mean(mpg)
) %>% do(
plot = plot_ly(
data = .,
x = ~!!sym(grouping_vars[1]),
y = ~mpg
) %>% add_bars(
name = ~am
)
) %>% subplot(
nrows = 1,
shareY = TRUE,
shareX = TRUE
)
# Remove all Xaxis Labels; ####
# Count number of unique values in grouping var;
no_unique <- mtcars %>%
select(grouping_vars[1]) %>%
unique() %>%
nrow()
gen_layout <- 1:no_unique %>% map(
.f = function(i) {
"some expression here"
}
)
base_plot %>%
gen_layout %>%
parse(text = .) %>%
eval()
}
但我认为必须有一个更优雅的解决方案。如果可能,最好使用plotly 或tidyverse 解决方案!
【问题讨论】: