4

I'm trying to create a climate graph with temperature as a line and precipitation as a bar plot. As the monthly temperatures are below zero the precipitation bars (which start at zero) are to high.

I want them to be at the lowest level of the temperature curve (around -25 on the first y axis) and the second y axis showing 0 at this point. Is there a way to move the data to fit?

#build data frame with temperature and precipitation data
df <- as.data.frame(c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
colnames(df) <- c("month")
df$month <- factor(df$month, levels = month.abb)
df$celsius <- c(-26.0, -24.5, -18.9, -9.8, -1.0, 7.0, 12.7, 12.3, 6.4, -1.2, -12.7, -21.9)
df$prec_mm <- c(18.7, 16.6, 18.1, 23.6, 30.0, 44.2, 59.8, 69.4, 69.9, 48.4, 35.5, 18.4)

#plot with ggplot2
library(ggplot2)

ggplot(data = df, mapping = aes(x = month, y = celsius, group = 1)) + 
geom_bar(mapping = aes(y = prec_mm/2), stat = "identity", color="blue", fill="blue", width = 0.5) + 
  geom_line(color="red", size=1.5) + 
  scale_y_continuous("Temperature [°C]", 
  sec.axis = sec_axis(~ . *2, name = "Precipitation [mm]")
  )

enter image description here

Richard
  • 72
  • 1
  • 7
  • Did you mean to replace `temp_churchill` with `df` in your `factor` call? – camille May 22 '19 at 14:55
  • 1
    Possible duplicate of [Plot with 2 y axes, one y axis on the left, and another y axis on the right](https://stackoverflow.com/questions/3099219/plot-with-2-y-axes-one-y-axis-on-the-left-and-another-y-axis-on-the-right) – qwr May 22 '19 at 14:55

1 Answers1

5

If I understood your question well, you want to rescale the axis to align the second scale to the zero-value of the first one. To do this:

  • Scale your data first to make all temperature measures positive.
  • Adjust the secondary axis scale to match the adjustment.

Here is your MWE adapted as mentioned:

#build data frame with temperature and precipitation data
df <- as.data.frame(c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
colnames(df) <- c("month")
df$month <- factor(temp_churchill$month, levels = month.abb)
df$celsius <- c(-26.0, -24.5, -18.9, -9.8, -1.0, 7.0, 12.7, 12.3, 6.4, -1.2, -12.7, -21.9)
df$prec_mm <- c(18.7, 16.6, 18.1, 23.6, 30.0, 44.2, 59.8, 69.4, 69.9, 48.4, 35.5, 18.4)

#plot with ggplot2
library(ggplot2)

ggplot(data = df, mapping = aes(x = month, y = prec_mm, group = 1)) + 
  geom_bar(stat = "identity", color="blue", fill="blue", width = 0.5) + 
  geom_line(mapping = aes(y = celsius+30), color="red", size=1.5) + # Scale data to match desired scale
  scale_y_continuous("Precipitation [mm]", 
                     sec.axis = sec_axis(~ . -30, name = "Temperature [°C]") # Reverse transformation to match data
  )

enter image description here

JohnBee
  • 1,720
  • 1
  • 15
  • 19