gpt4 book ai didi

r - 是否可以使用 ggplot2 修复轴边距?

转载 作者:行者123 更新时间:2023-12-04 12:20:41 26 4
gpt4 key购买 nike

我有一个由条形图组成的交互式显示器,该条形图显示了不同类别的选定统计数据。然而,ggplot2根据标签重新调整 y 轴宽度,从而使条形烦人地在 x 方向上移动。参见示例:

library(shiny)
library(dplyr)
library(ggplot2)

shinyApp(
ui = bootstrapPage(
selectInput('statistic', label='Chose a statistic', choices=c('carat', 'depth', 'table', 'price')),
plotOutput('plot')
),
server = function(input, output) {
output$plot <- renderPlot(
diamonds %>%
ggplot(aes(x=color, y=get(input$statistic))) +
geom_bar(stat = 'sum') +
theme(text = element_text(size=20), legend.position="none")
)
}
)

如何修复 y 轴标签的宽度? (或等效的绘图面板的宽度?)

我确实找到了相关问题,但都在静态上下文中解决了,例如 with facets或与 gtable .

最佳答案

一种方法是提供一个标签函数,通过用空格填充标签宽度来规范化标签宽度。 function(label) sprintf('%15.2f', label)将在左侧填充 15 个空格并打印带有 2 个小数位的数值。

library(shiny)
library(dplyr)
library(ggplot2)

shinyApp(
ui = bootstrapPage(
selectInput('statistic', label='Chose a statistic', choices=c('carat', 'depth', 'table', 'price')),
plotOutput('plot')
),
server = function(input, output) {
output$plot <- renderPlot(
diamonds %>%
ggplot(aes(x=color, y=get(input$statistic))) +
scale_y_continuous(labels=function(label) sprintf('%15.2f', label)) +
geom_bar(stat = 'sum') +
theme(text = element_text(size=20), legend.position="none")
)
}
)

关于r - 是否可以使用 ggplot2 修复轴边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34677551/

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