如何更改 R 中 ggplotly 中的图例位置

2023-12-27

下面的代码使用生成两个图ggplot and ggplotly。尽管使用layout()对于 ggplotly,图例仍然位于右侧。图例必须位于底部。任何人都可以帮助将图例移动到 ggplotly 的底部吗?我已经尝试过解决方案R+shiny+plotly:ggplotly将图例向右移动 https://stackoverflow.com/questions/69306154/r-shiny-plotly-ggplotly-moves-the-legend-to-the-right并且不在这里工作。如果我错过了显而易见的事情,有人可以帮忙吗?

measure<-c("MSAT","MSAT","GPA","MSAT","MSAT","GPA","GPA","GPA")
score<-c(500, 490, 2.9, 759, 550, 1.2, 3.1, 3.2)
data<-data.frame(measure,score)


ui <- fluidPage(
  mainPanel(
    plotOutput("myplot" ),
    plotlyOutput("myplot2" )
  )
)

server <- function(input, output) {
  myplot <- reactive({
    gpl1 <- ggplot(data,aes(y=reorder(measure, score),x=score,fill=score)) +
      geom_bar(stat="identity")+
      theme(legend.position="bottom")+
      xlab("x")+
      ylab("y")+
      labs(title = NULL)
    gpl1
  })
  
  myplot2 <- reactive({
    gpl2 <- ggplot(data,aes(y=reorder(measure, score),x=score,fill=score)) +
      geom_bar(stat="identity") +
      theme(legend.position="bottom")+
      xlab("x")+
      ylab("y")+
      labs(title = NULL)
    ggplotly(gpl2) %>% 
      layout(legend = list(orientation = 'h', x = 0.45, y = 1.1))
  })
  output$myplot <- renderPlot({
    myplot()
  })
  output$myplot2 <- renderPlotly({
    myplot2()
  })
}
  
shinyApp(ui = ui, server = server)

这里的问题是,你正在处理一个colorbar不是传奇。

目前正在密谋不提供水平颜色条 https://github.com/plotly/plotly.js/issues/1244.

在 ggplotly 上下文中,更改颜色条的位置似乎也有问题:

library(shiny)
library(plotly)

measure<-c("MSAT","MSAT","GPA","MSAT","MSAT","GPA","GPA","GPA")
score<-c(500, 490, 2.9, 759, 550, 1.2, 3.1, 3.2)
data<-data.frame(measure,score)


ui <- fluidPage(
  mainPanel(
    plotOutput("myplot" ),
    plotlyOutput("myplot2" )
  )
)

server <- function(input, output) {
  myplot <- reactive({
    gpl1 <- ggplot(data,aes(y=reorder(measure, score),x=score,fill=score)) +
      geom_bar(stat="identity")+
      theme(legend.position="bottom")+
      xlab("x")+
      ylab("y")+
      labs(title = NULL)
    gpl1
  })
  
  myplot2 <- reactive({
    fig <- ggplotly(myplot())
    fig <- style(fig, marker = list(colorbar = list(xanchor = "center", yanchor = "center", x = 0.5, y = -1, title = "test")), traces = NULL) # try traces = 1 or 1:2
    # browser()
    # plotly_json(fig)
  })
  
  output$myplot <- renderPlot({
    myplot()
  })
  
  output$myplot2 <- renderPlotly({
    myplot2()
  })
}

shinyApp(ui = ui, server = server)

因此,目前我建议不要修改颜色条并使用默认值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何更改 R 中 ggplotly 中的图例位置 的相关文章

随机推荐