You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 20:57:03