Formatting ggplot2 axis labels with commas (and K? MM?) if I already have a y-scale

前端 未结 1 746
野性不改
野性不改 2020-12-24 06:23

I am trying to format Cost and Revenue (both in thousands) and Impressions (in millions) data for a ggplot graph\'s y-axis labels.

My plot runs from 31 days ago to

相关标签:
1条回答
  • 2020-12-24 06:59

    For the comma formatting, you need to include the scales library for label=comma. The "error" you discussed is actually just a warning, because you used both ylim and then scale_y_continuous. The second call overrides the first. You can instead set the limits and specify comma-separated labels in a single call to scale_y_continuous:

    library(scales)
    
    ggplot(df, aes(x = Date, y = Cost))+
      geom_line(lwd = 0.5) +
      geom_line(aes(y = Cost_7), col = 'red', linetype = 3, lwd = 1) +
      geom_line(aes(y = Cost_30), col = 'blue', linetype = 5, lwd = 0.75) +
      xlim(c(left, right)) + 
      xlab("") +
      scale_y_continuous(label=comma, limits=c(min(df$Cost[df$Date > left]), 
                                               max(df$Cost[df$Date > left])))
    

    Another option would be to melt your data to long format before plotting, which reduces the amount of code needed and streamlines aesthetic mappings:

    library(reshape2)
    
    ggplot(melt(df, id.var="Date"), 
           aes(x = Date, y = value, color=variable, linetype=variable))+
      geom_line() +
      xlim(c(left, right)) + 
      labs(x="", y="Cost") +
      scale_y_continuous(label=comma, limits=c(min(df$Cost[df$Date > left]), 
                                               max(df$Cost[df$Date > left])))
    

    Either way, to put the y values in terms of thousands or millions you could divide the y values by 1,000 or 1,000,000. I've used dollar_format() below, but I think you'll also need to divide by the appropriate power of ten if you use unit_format (per @joran's suggestion). For example:

    div=1000
    
    ggplot(melt(df, id.var="Date"), 
           aes(x = Date, y = value/div, color=variable, linetype=variable))+
      geom_line() +
      xlim(c(left, right)) + 
      labs(x="", y="Cost (Thousands)") +
      scale_y_continuous(label=dollar_format(),
                         limits=c(min(df$Cost[df$Date > left]), 
                                  max(df$Cost[df$Date > left]))/div)
    

    Use scale_color_manual and scale_linetype_manual to set custom colors and linetypes, if desired.

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