ggplot: align plots together and add common labels and legend

前端 未结 1 436
-上瘾入骨i
-上瘾入骨i 2021-01-27 08:50

I have a data.frame in which one variable has many levels (e.g. param1, param2and param3). All these levels have the same uni

相关标签:
1条回答
  • 2021-01-27 09:35

    I think you can everything you want using only ggplot2, including a shared x-axis, shared axis titels and proper spacing. To me that seems easier than messing around with gtables.

    This is a perfectly fine attempt:

    ggplot(df[df$cut %in% c("Fair", "Ideal"),], aes(x=carat , y= new_price, color = color))+
      geom_point(alpha = 0.3)+
      scale_y_continuous(labels = fmt_dcimals(2))+
      scale_x_continuous(limits = c(0,5.2), breaks=c(0,1,2,3,4,5), labels = fmt_dcimals(2))+
      facet_wrap(~cut, scales = 'free_y', nrow = 2) +
      labs(x = "",
           y = "")
    

    If you really want to have custom breaks, you can use a break function to supply those:

    make_breaks <- function(ranges) {
      if(ranges[2] > 1) {
        c(0, 250,500,750,1000, 1250, 1500, 1750, 2000)
      } else {
        c(0, 0.05,0.1,0.15,0.2)
      }
    }
    
    ggplot(df[df$cut %in% c("Fair", "Ideal"),], aes(x=carat , y= new_price, color = color))+
      geom_point(alpha = 0.3)+
      scale_y_continuous(labels = fmt_dcimals(2), breaks = make_breaks)+
      scale_x_continuous(limits = c(0,5.2), breaks=c(0,1,2,3,4,5), labels = fmt_dcimals(2))+
      facet_wrap(~cut, scales = 'free_y', nrow = 2) +
      labs(x = "",
           y = "")
    

    0 讨论(0)
提交回复
热议问题