R+Shiny+Plotly环境下ggplotly将图例移至右侧的问题咨询
解决方案
ggplotly() 不会完全继承ggplot2主题中设置的图例位置参数,需要额外调用plotly的layout()函数手动指定图例的位置和排布方式即可解决该问题。
你仅需要修改生成交互式图表的代码段,在ggplotly()返回结果后链式调用layout(),配置图例参数:
# 原代码 ggplotly(gpl2) # 修改为 ggplotly(gpl2) %>% layout( legend = list( orientation = "h", # 设置图例为水平排布 y = 1.1, # 调整图例垂直位置,数值越大位置越靠上 x = 0.5 # 调整图例水平位置,0.5为居中对齐 ) )
修改后完整的可运行代码如下:
library(shiny) library(plotly) library(ggplot2) library(dplyr) df <- tibble(x=seq(20), y=seq(20), type=c(rep("a", 10), rep("b", 10))) ui <- fluidPage( mainPanel( plotOutput("myplot" ), plotlyOutput("myplot2" ) ) ) server <- function(input, output) { myplot <- reactive({ gpl1 <- df%>% ggplot(aes(x = x, y = y, fill=type)) + geom_col()+ theme(legend.position="top")+ xlab("x")+ ylab("y")+ labs(title = NULL) gpl1 }) myplot2 <- reactive({ gpl2 <- df%>% ggplot(aes(x = x, y = y, fill=type)) + geom_col()+ theme(legend.position="top")+ xlab("x")+ ylab("y")+ labs(title = NULL) # 仅修改此处即可 ggplotly(gpl2) %>% layout( legend = list( orientation = "h", y = 1.1, x = 0.5 ) ) }) output$myplot <- renderPlot({ myplot() }) output$myplot2 <- renderPlotly({ myplot2() }) } shinyApp(ui = ui, server = server)
如果图例位置偏移不符合你的预期,可以自行调整y和x的数值适配布局。
内容的提问来源于stack exchange,提问作者larry77
相关产品推荐
相关产品推荐

