Is there a way of manipulating ggplot scale breaks and labels?

前端 未结 2 614
北恋
北恋 2020-11-29 23:06

ggplot generally does a good job of creating sensible breaks and labels in scales.

However, I find that in plot with many facets and perhaps a for

2条回答
  •  时光取名叫无心
    2020-11-29 23:53

    You can pass in arguments such as min() and max() in your call to ggplot to dynamically specify the breaks. It sounds like you are going to be applying this across a wide variety of data so you may want to consider generalizing this into a function and messing with the formatting, but this approach should work:

    ggplot(df, aes(x=x)) + 
      geom_bar(binwidth=0.5) + 
      facet_grid(~fac) + 
      scale_x_continuous(breaks = c(min(df$x), 0, max(df$x))
        , labels = c(paste( 100 * round(min(df$x),2), "%", sep = ""), paste(0, "%", sep = ""), paste( 100 * round(max(df$x),2), "%", sep = ""))
        )
    

    or rotate the x-axis text with opts(axis.text.x = theme_text(angle = 90, hjust = 0)) to produce something like:

    enter image description here

    Update

    In the latest version of ggplot2 the breaks and labels arguments to scale_x_continuous accept functions, so one can do something like the following:

    myBreaks <- function(x){
        breaks <- c(min(x),median(x),max(x))
        names(breaks) <- attr(breaks,"labels")
        breaks
    }
    
    ggplot(df, aes(x=x)) + 
      geom_bar(binwidth=0.5) + 
      facet_grid(~fac) + 
      scale_x_continuous(breaks = myBreaks,labels = percent_format()) + 
      opts(axis.text.x = theme_text(angle = 90, hjust = 1,size = 5))
    

提交回复
热议问题