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

时间:2018-01-05 21:28:08

标签: r ggplot2 animated-gif

我在ggplot2中制作了直方图集合,并使用ImageMagick将它们设置为gif动画。 animated gif of graphs made in ggplot2 我们的想法是假设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")

2 个答案:

答案 0 :(得分:6)

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

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")

base_plots


# 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")

limits

但是,如果你另外选择,我会用白色空格填充轴标签:

# 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")

labels

随意询问是否有任何不清楚的事情。

答案 1 :(得分:4)

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

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"))