
我们的想法是假设x轴刻度在所有图形中都是相同的,但这并不完全正确,因为y轴由于标签的宽度变化而摇摆不定.如何锚定图形以使所有图形具有完全相同的轴位置?
这是我的ggplot代码,如果它有帮助:
hist.fn<-function(tIEr,ddf){ df<-ddf[ddf$tIEr==tIEr,] l<-match(tIEr,levels(df$tIEr)) hist.png<-ggplot(df,aes(df$"Premium Adult IndivIDual Age 40" ))+ geom_histogram()+ labs(Title=paste0(tIEr," premiums in federal exchanges"),x ="Premium",y = "Frequency")+ coord_cartesian(xlim=c(0,1500))+ theme_bw()+ theme(text = element_text(size=14),plot.Title = element_text(face="bold"),axis.Title.x =element_text(face="bold"),axis.Title.y =element_text(face="bold")) file=paste0(l,"hist.jpg") ggsave(filename=file,plot=hist.png,wIDth=13,height=8,dpi=50) return(hist.png)}data.df$tIEr%>% levels %>% lapply(FUN=hist.fn,ddf=data.df) ->histograms.of.tIErs system("magick -delay 75 *hist.jpg hist.gif")解决方法 首先,我想指出,由于y轴值不同,情节可能会产生误导.观众的注意力主要是直方图,而不是价值观. 因此,我强烈建议在所有图上固定y轴.
library(ggplot2)library(grIDExtra)library(stringr)# Generate plots # For each SpecIEs in iris dataset - generate a histogram of the Petal's lengthplots = lapply(levels(iris$SpecIEs),function(spec){ ggplot(iris[iris$SpecIEs == spec,],aes(Petal.Length)) + geom_histogram() + ggtitle(spec) })# Show plots sIDe by sIDe grID.arrange(grobs = plots,nrow = 1,ncol = 3,top = "Base\n\n") .
.
# Solution 1 (recommended) - Set the same y-axis range for all the plots alignlimits = function(plotsList){ # Extract limits of y-axis for each plot y.limits = sapply(plotsList,function(.){layer_scales(.)$y$range$range}) y.min = min(y.limits[1,]) # Minimum of all the ranges y.max = max(y.limits[2,]) # Maximum of all the ranges # Apply new limits for each plot return(lapply(plotsList,function(.){. + coord_cartesian(ylim=c(y.min,y.max))}))}# Align limits of original plots and displayplots.limits = alignlimits(plots)grID.arrange(grobs = plots.limits,top = "Aligned limits\n\n") .
但是,如果你选择其他方法,我会用白色空格填充轴标签:
# Use whitespaces to pad alignLables = function(plotsList){ # Extract labels of y-axis # Note: Don't use the as.character on the maximum limit,# as decimal places in labels may increase the character count y.labels = lapply(plotsList,function(.){ggplot_build(.)$layout$panel_ranges[[1]]$y.labels}) # Calculate the maximum number of characters for each plot's labels maxChars = sapply(y.labels,function(.){max(nchar(.))}) # define a function that would space-pad the labels and apply format.labels = function(label){str_pad(label,max(maxChars),pad = " ")} return(lapply(plotsList,function(.){return(. + scale_y_continuous(labels = format.labels))}))}# Align labels of original plots and displayplots.labels = alignLables(plots)grID.arrange(grobs = plots.labels,top = "Aligned labels\n\n") 随意询问是否有任何不清楚的事情.
总结以上是内存溢出为你收集整理的r – 如何在ggplot2中设置y轴标签的宽度全部内容,希望文章能够帮你解决r – 如何在ggplot2中设置y轴标签的宽度所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)