Search code examples
rggplot2geom-barpolar-coordinates

Bar graphs that don't start at 0 in R


I'm trying to show the available range of travel of a machine that has 360 degrees of rotation and that has another axis of motion with a range of -5 to 152 that is independent of yaw. All of the bar graph drawing functions I can find assume that data start at 0 and this leaves a hole in the middle of the graph between -5 and 0. Is it possible to tell geom_bar() or geom_col() to start drawing at -5 instead of 0?

Here is the code that I'm using and an example graph.

df <- data.frame(0:360)
colnames(df) = "Yaw"
df$Max.Static <- ((runif(361) * 157)-5)

library(ggplot2)

ggplot(df, aes(x =Yaw , y = Max.Static)) + 
  geom_col(width = 1, alpha = .5 , fill = "#69B600") + 
  scale_y_continuous(
    limits = c(-5,152),
    breaks = seq(0,140,20)
    ) +
  scale_x_continuous(
    limits = c(-1,361),
    breaks = seq(0,360,45),
    minor_breaks = seq(0,360,15)
    ) +
  coord_polar(theta = "x") +
  labs(x = NULL, y = NULL) + 
  theme(axis.text.y = element_blank(),
        axis.ticks = element_blank())

enter image description here


Solution

  • Bit of a weird hack, but the following works if you can tolerate a warning:

    df <- data.frame(0:360)
    colnames(df) = "Yaw"
    df$Max.Static <- ((runif(361) * 157)-5)
    
    library(ggplot2)
    
    ggplot(df, aes(x =Yaw , y = Max.Static)) + 
      geom_col(width = 1, alpha = .5 , fill = "#69B600",
               aes(ymin = after_scale(-Inf))) + ######## <- Change this line
      scale_y_continuous(
        limits = c(-5,152),
        breaks = seq(0,140,20)
      ) +
      scale_x_continuous(
        limits = c(-1,361),
        breaks = seq(0,360,45),
        minor_breaks = seq(0,360,15)
      ) +
      coord_polar(theta = "x") +
      labs(x = NULL, y = NULL) + 
      theme(axis.text.y = element_blank(),
            axis.ticks = element_blank())
    #> Warning: Ignoring unknown aesthetics: ymin
    

    Created on 2021-01-20 by the reprex package (v0.3.0)

    It works because we can access the rectangle parameters (xmin, xmax, ymin, ymax) after the bar parametrisation has been converted to rectangles with after_scale().

    The -Inf instructs ggplot that the variable should be at the minimum of the scale (even after expansion), hence closing the gap.