提问人:Lana Meijinhos 提问时间:11/15/2023 更新时间:11/17/2023 访问量:42
在不使用 shiny 的情况下将下拉列表添加到 RMarkdown HTML 文件中的 ggplot?
Add dropdown filter list to ggplot in RMarkdown HTML file WITHOUT using shiny?
问:
我正在使用 RMarkdown 创建一个 HTML 文件,其中包含一些交互式绘图。在一些帮助下,我必须创建一个下拉列表来过滤更改绘图的变量,但它使用 shiny,因此我无法将其呈现为 HTML 文件。有什么方法可以在不使用 shiny 的情况下添加下拉列表,以便我可以拥有我的 HTML 文件?
代码:
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(ggplot2)
library(plotly)
# data
data <- data.frame(
anoobito = sample(2019:2023),
diadasemana = sample(c("Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"), 23000, replace = TRUE)
)
dia <- data %>%
group_by(anoobito, diadasemana) %>%
tally %>%
mutate(diadasemana = factor(diadasemana, levels = c("Domingo","Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado")))
# Create a ggplot object
gg <- ggplot(dia, aes(x = diadasemana, y = n, group = anoobito)) +
geom_line(aes(color = anoobito), size = 2) +
geom_point(aes(color = anoobito), size = 3) +
theme_minimal(base_size = 15) +
scale_y_continuous(limits = c(0,1000), expand = expansion(mult = c(0, .1))) +
theme(legend.position = "bottom",
axis.line = element_line(colour = "black"),
axis.text.x=element_text(colour="black"), axis.text.y=element_text(colour="black")) +
labs(
x = "Ano do Óbito", # label do eixo X
y = "Número de Óbitos",
caption = "**Fonte**: SIM, SMS-RJ. Dados sujeitos a alterações.")
# Create a plotly object from ggplot
p <- ggplotly(gg)
# Add a dropdown list for the variable "anoobito"
p <- p %>% layout(showlegend = F,
updatemenus = list(
list(
x = 1.5,
y = 0.8,
buttons = list(
list(method = "restyle",
args = list("visible", list(TRUE, FALSE, FALSE, FALSE, FALSE)),
label = "2019"),
list(method = "restyle",
args = list("visible", list(FALSE, TRUE, FALSE, FALSE, FALSE)),
label = "2020"),
list(method = "restyle",
args = list("visible", list(FALSE, FALSE, TRUE, FALSE, FALSE)),
label = "2021"),
list(method = "restyle",
args = list("visible", list(FALSE, FALSE, FALSE, TRUE, FALSE)),
label = "2022"),
list(method = "restyle",
args = list("visible", list(FALSE, FALSE, FALSE, FALSE, TRUE)),
label = "2023")
)
)
)
)
p
看起来很奇怪。我想删除图例,当我选择 2019 年时,它应该只显示 2019 年,而不是所有年份。剧情没有显示geom_point。
答:
2赞
Adriano Mello
11/15/2023
#1
您看不到选择年份的时间,对吧?
GGplot被认为是连续的。试着让它们成为因素,就像:geom_point()
anoobito
diadasemana
dia <- data %>%
group_by(anoobito, diadasemana) %>%
tally %>%
mutate(
anoobito = factor(anoobito, levels = 2019:2023),
diadasemana = factor(diadasemana, levels = c("Domingo","Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado")))
当心意大利面图形!
下一个:禁止函数的输出
评论
geom_point()