我正在使用ggplot2处理包含Shiny元素的RMarkdown报告,并使用ggplotly转换其图表。 在常规的RMarkdown报告中,一切都完美无缺。 ggplotly does not allow您可以在底部放置一个水平图例,但是我仍然设法做到了,using this answer。
现在情节看起来不错
此图的代码为
semiformal_savings_chart <- ggplot(semiformal_savings, aes(x = Country, y =
Percent, fill = Category)) +
geom_bar(stat = 'identity', width = 0.7) +
theme_tufte() +
scale_fill_brewer(palette = "Paired") +
theme(axis.title.y = element_blank()) +
theme(axis.title.x = element_blank()) +
ylim(0, 80) +
theme(legend.text = element_text(size = 12)) +
theme(axis.text.x = element_text(size = 12)) +
theme(axis.text.y = element_text(size = 12)) +
theme(plot.margin = margin(0.1, 0.1, 0.1, 0.1, "cm"))
ggplotly(semiformal_savings_chart) %>% config(displayModeBar = F) %>%
layout(legend = list(orientation = "h", x = 0.4, y = -0.2))
当我将其放入Shiny格式时,我不得不使用ggplotly删除最后两行代码,这将禁用Plotly面板。只是通过管道将其连接到ggplot不能正常工作,并且出现错误。
错误:没有将适用于“布局”的方法应用于类“ c('theme','gg')”的对象
反应性非常好,但是在Shiny中,我的情节右边有Plotly面板+图例,我不喜欢。
Shiny代码看起来像这样
semiformal_savings_data <- reactive({
filter(semiformal_savings,
Country %in% input$Country)
selectInput(inputId = "Country", label = "Please select a
country/countries", choices = unique(semiformal_savings$Country),
selected = unique(semiformal_savings$Country), multiple = TRUE)
plotlyOutput("semiformalsavingsPlot")
output$semiformalsavingsPlot <- renderPlotly({
ggplot(semiformal_savings_data(), aes(x = Country, y = Percent, fill =
Category)) + geom_bar(stat = 'identity', width = 0.7) +
theme_tufte() +
scale_fill_brewer(palette = "Paired") +
theme(axis.title.y = element_blank()) +
theme(axis.title.x = element_blank()) +
ylim(0, 80) +
theme(legend.text = element_text(size = 12)) +
theme(axis.text.x = element_text(size = 12)) +
theme(axis.text.y = element_text(size = 12)) +
theme(plot.margin = margin(0.1, 0.1, 0.1, 0.1, "cm"))
})
但是这部分现在丢失了
%>% config(displayModeBar = F) %>% layout(legend = list(orientation = "h",
x = 0.4, y = -0.2))
如何将此功能附加到我近乎完美的情节上?
谢谢!
答案 0 :(得分:0)
亲自解决
更改很小,我仍然使用ggplotly()
g1 <- ggplot(ownership_data(), aes(x = as.character(Year), y = Percent, fill =
Category)) +
geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ Country) +
theme_tufte() +
ylim(0, 100) +
scale_fill_brewer(palette = "Paired") +
theme(axis.title.y = element_blank()) +
theme(axis.title.x = element_blank()) +
theme(legend.text = element_text(size = 13)) +
theme(axis.text.x = element_text(size = 12)) +
theme(axis.text.y = element_text(size = 13)) +
theme(strip.text.x = element_text(size = 12)) +
theme(legend.position = "bottom") +
theme(legend.title = element_blank())
return(ggplotly(g1, tooltip = c("y", "text")) %>% config(displayModeBar = F) %>%
layout(legend = list(orientation = "h", x = 0.4, y = -0.2)))