本文介绍了用ggplot2修正坐标轴余量有可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个交互式显示,包含一个条形图,显示不同类别的选定统计信息。但是, ggplot2 会根据标签重新调整y轴的宽度,从而使条纹令人讨厌地沿着x方向移动。例子: library(shiny) library(dplyr) library(ggplot2) shinyApp( ui = bootstrapPage()selectInput('statistic',label ='选择统计量',选项= c('carat','depth','table',' ('plot')), server = function(输入,输出){输出$ plot )钻石%>% 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 。 解决方案一种方法是提供标签函数,通过用空格填充标签宽度来标准化标签宽度。 函数(标签)sprintf('%15.2f',label)将填充左边的15个空格并打印带2个小数位的数字值。 library(shiny) library(dplyr) library(ggplot2) shinyApp( ui = bootstrapPage( selectInput('statistic',label ='选择统计量',选择= c('克拉','深度','表格','价格')), plotOutput('plot')), server = function(输入,输出){输出$ plot 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))} ) I have an interactive display consisting of a bar chart that shows a selected statistic for different categories. However, ggplot2 readjusts the y-axis width depending on the labels, and hence makes the bars annoyingly move on the x-direction. See exemple: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") ) })How can I fix the width of the y-axis label? (or equivalently the width of the plotting panel?)I did find related questions, but all were solved in a static context, for instance with facets or with gtable. 解决方案 One way would be to provide a label function that normalizes the label widths by padding them with spaces. function(label) sprintf('%15.2f', label) would pad with 15 spaces on the left and print the numeric value with 2 decimal places.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") ) }) 这篇关于用ggplot2修正坐标轴余量有可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 20:35
查看更多