M. Wein
M. Wein

Reputation: 33

How to scale a secondary axis with ggplot2, second axis has negative values

When I plot the secondary y-axis, the negative values in the data set drop below the other plotted data. I was trying to have both data sets start on the same baseline but have different axes scales.

I have tried scaling the data, but I cannot achieve my goal. I'm not very experienced with the ggplot2 package. With the code shown, I believe I'm plotting the temperature data on the same scale as precipitation.

# Enter climate data to be graphed
month <- month.abb[c(1,2,3,4,5,6,7,8,9,10,11,12)]
month <- ordered(month, month.abb)
aveT <- c(-2.7, -0.9, 3.1, 7.3, 11.9, 15.7, 20.2, 19.8, 14.4, 7.6, 1.2, -3.6)
precip <- c(46.2, 30.5, 23.9, 21.1, 41.1, 40.1, 26.7, 21.6, 24.6, 22.4, 36.6, 38.6)

#Set the dataframe
df <- data.frame(month, aveT, precip)

#Graph precipitation data as bar graph
g <- ggplot(df) 
g <- g + geom_bar(aes(x=month, y=precip), stat="identity", fill="blue", color="black") + theme_bw() + theme(panel.grid = element_blank())
g <- g + ylim(0, 50)

#Add Temperature data
g <- g + geom_line(aes(x=month, y=aveT, group=1), color="red", size=1.5)
g <- g + scale_y_continuous(sec.axis = sec_axis(~.*1, name = "Temperature (C)"))

The result is the temperature line graph's negative values dip below the precipitation bar graph values. I want to get the primary axis go from 0 to 50, and the secondary axis from -5 to 25, but start in the same position.

resulting graph

Upvotes: 3

Views: 5544

Answers (1)

busybear
busybear

Reputation: 10590

Setting the secondary scale does not alter the second line you created. You need to transform the data then plot and adjust the secondary axis by doing the inverse of your transform.

For the following example, we want to go from y limits of 0 => 50 to -5 => 20. To do this, we transform the y axis values with aveT = y / 2 - 5 to get the new valeus for aveT. To transform the original aveT data points, we have to do the inverse tranformation: y = (aveT + 5) * 2. So this is what the code should look like:

g <- g + geom_line(aes(x=month, y=(aveT + 5) *2 , group=1), color="red", size=1.5)
g <- g + scale_y_continuous(sec.axis = sec_axis(~./2-5, name = "Temperature (C)"))

enter image description here

Upvotes: 4

Related Questions