gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:37:01 27 4
gpt4 key购买 nike

下面的代码使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com