在我的 Shiny 应用程序中,我想要有多个交互式绘图。我使用 ggplot 创建绘图对象,然后将其传递给 ggplotly 以添加交互式元素。为了最大化绘图空间,我希望图例位于绘图下方。当我将图例移至底部时,它会遮挡部分 x 轴。如何将图例放置在 x 轴标签的正下方?我希望我知道当标题成为一个情节对象时如何包装标题或让副标题保持不变。另外,有没有办法移动绘图标题,以便当用户与绘图交互时它不会隐藏在绘图工具后面? 这是一个小例子:
library(shiny)
library(ggplot2)
library(plotly)
# adding a categorical variable to the faithful dataset
myfaithful <- faithful %>%
mutate(duration = if_else(eruptions <= 2,
"short",
"long")) %>%
mutate(duration = factor(duration, levels = c("short", "long"),
ordered = TRUE))
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel(
"Stackoverflow example app"
),
# Sidebar
sidebarLayout(
sidebarPanel(
width = 2,
radioButtons("box",
label = "Some sidebar content",
choices = LETTERS[1:10])
),
#
mainPanel(
width = 10,
uiOutput("plots"))
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$plots <- renderUI({
fluidRow(
column(6,
wellPanel(
uiOutput("distPlot")
)
),
column(6,
wellPanel(
"Panel 2"
)
)
)
})
output$distPlot <- renderUI({
#
p <- ggplot(myfaithful, aes(x = waiting, fill = duration)) +
geom_bar() +
labs(title = "Frequency of time elapsed between eruptions, by length of eruption, long title",
subtitle = "Does a subtitle work?",
x = "Time (min)",
y = "Frequency",
fill = "Duration") +
theme(legend.position = "bottom")
ggplotly(p) %>%
plotly::layout(
xaxis = list(title = "Time(min)",
tickangle = 45),
legend=list(
orientation='h'),
title = list(
font = list(
family = "Arial",
color = "black",
size = 16),
text = "Frequency of time elapsed between eruptions, by length of eruption, long title"
)
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
解决此问题的一种方法是增加“纸张”或网格空间周围的边距,然后调整标题和图例的位置。长标题在一些小型设备中仍然是一个问题,因为据我所知,Plotly 在任何标签中都没有长字符串的换行选项。要中断字符串,您可以添加 html 中断
<br>
。
我会删除 ggplot 中的标签定义,只在
plotly::layout()
中定义它们,以避免重复指令。
您可以在 Plotly 的文档中找到如何定位标题和图例的详细信息https://plotly.com/r/reference/layout/
output$distPlot <- renderUI({
p <- ggplot(myfaithful, aes(x = waiting, fill = duration)) +
geom_bar()
ggplotly(p) %>%
plotly::layout(
xaxis = list(
title = list(text = "Time(min)", font = list(size = 12)),
tickangle = 45
),
yaxis = list(
title = list(text ="Frequency", font = list(size = 12))
),
legend = list(
orientation = "h",
y = -.25
),
title = list(
font = list(family = "Arial", color = "black", size = 14),
text = "Frequency of time elapsed between eruptions, <br> by length of eruption, long title",
yref = "paper",
yanchor = "bottom",
pad = list(b = 30),
y = 1
),
autosize = TRUE,
margin = list(t = 90, r = 10, b = 90, l = 50)
)
})