首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在ggplot2中设置y轴标签的宽度

如何在ggplot2中设置y轴标签的宽度
EN

Stack Overflow用户
提问于 2018-01-06 05:28:08
回答 2查看 3.3K关注 0票数 8

我在ggplot2中收集了一组直方图,并使用ImageMagick将它们动画化为gif。

我们的想法是,x轴比例在所有图表中都应该是相同的,但这并不完全正确,因为由于标签的宽度不同,y轴会左右摆动。如何锚定图形,使所有图形具有完全相同的轴位置?

下面是我的ggplot代码,如果它有用的话:

代码语言:javascript
运行
复制
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")
EN

回答 2

Stack Overflow用户

发布于 2018-01-06 09:02:29

首先,我想指出的是,由于y轴值的不同,绘图可能会误导。观众的注意力将主要集中在直方图上,而不是值上。因此,我强烈建议在所有地块上固定y轴。

代码语言:javascript
运行
复制
library(ggplot2)
library(gridExtra)
library(stringr)

# Generate plots 
# For each Species in iris dataset - generate a histogram of the Petal's length
plots = 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")

代码语言:javascript
运行
复制
# 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 display
plots.limits = alignLimits(plots)
grid.arrange(grobs = plots.limits, nrow = 1, ncol = 3, top = "Aligned limits\n\n")

但是,如果您选择其他方式,我会使用空格填充轴标签:

代码语言:javascript
运行
复制
# 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 display
plots.labels = alignLables(plots)
grid.arrange(grobs = plots.labels, nrow = 1, ncol = 3, top = "Aligned labels\n\n")

如果有什么不清楚的地方,请随时询问。

票数 7
EN

Stack Overflow用户

发布于 2018-01-06 10:01:22

通过将绘图转换为gtable,很容易设置固定的宽度,请注意这不是一个稳定的界面,因此将来可能会停止工作。

代码语言:javascript
运行
复制
library(ggplot2)
library(grid)
library(gridExtra)

plot_random <- function(){
  ggplot() +
    labs(y=paste(letters[sample(1:24, sample(1:3))], collapse = "\n"))
}

pl <- replicate(3, plot_random(), simplify = FALSE)
gl <- lapply(pl, ggplotGrob)
wl <- lapply(gl, function(g) g$widths[4])
wmax <- do.call(unit.pmax, wl)
gl <- lapply(gl, function(g) {g$widths[4] <- wmax; g})

grid.arrange(arrangeGrob(grobs = pl, top = "Normal case"),
             arrangeGrob(grobs = gl, top = "Standardised left"))
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48121528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档