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

标签 r ggplot2 r-plotly ggplotly

下面的代码使用 ggplotggplotly 生成两个图。尽管使用 layout() 到 ggplotly,图例仍然在右侧。图例必须位于底部。谁能帮助将图例移到 ggplotly 的底部?我已经尝试了 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)

最佳答案

好的,这不是一个完整的答案,但它是一个可以帮助其他人查明问题的开始,而且它太长了,无法放入评论中。可能值得提出一个问题,尽管我不确定问题出在哪里(即在什么包内)。

我重新运行了 R + shiny + plotly: ggplotly moves the legend to the right 中的代码它可以正常工作,但由于某种原因你的没有。唯一的区别是您的 fill 是连续的,而 fill 是分类的。

如果您在此处为分数添加分类组:

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,score.f=as.factor(score))

然后您的代码就可以工作了。你需要用fill=score.f修改gpl2对象(而不是fill=score),同时也需要改变y值在布局中将图例置于底部:

ggplotly(gpl2) %>% 
            layout(legend = list(orientation = 'h', x = 0.45, y = -.07))

enter image description here

然而,一旦您将填充组更改为连续

score<-c(500, 490, 2.9, 759, 550, 1.2, 3.1, 3.2)
data<-data.frame(measure,score,score.f=score)

传说可以追溯到右边:

enter image description here

关于r - 如何在 R 中的 ggplotly 中更改图例位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69484878/

相关文章:

r - 为什么在使用observeEvent 和此函数时收到错误消息,该函数在未包装在观察者中时工作正常?

r - 使用 R pheatmap 包时有没有办法关闭聚类?

r - 更改 ggplot 中图例形状的填充

r - 如何正确解释 ggplot 的 stat_density2d

r - 控制 ggplot2 图中点的相对大小

r - 格式化悬停数据标签 Plotly R

R 插入符 : "non-numeric argument to binary operator" in train with qrf

删除嵌套列表中的重复项

删除 Plotly 中条形之间的间隙

r - 如何在漏斗图中具有固定大小但动态悬停文本?