Let's consider a scenario where we are plotting data related to a city's monthly climate. On the X-axis, we have months from January to December. We want to track both the average monthly temperature (in degrees Celsius) and the average monthly rainfall (in millimeters) for the city. Given that these two variables have vastly different scales, we'll use two separate Y axes.
Try the following code:
# Creating mock data
months <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
avg_temp <- c(5, 6, 10, 15, 20, 24, 26, 25, 21, 16, 10, 6) # Monthly average temperature in degrees Celsius
avg_rainfall <- c(60, 50, 55, 40, 30, 20, 25, 20, 30, 40, 50, 60) # Monthly average rainfall in millimeters
# Installing and loading necessary packages
install.packages("ggplot2")
library(ggplot2)
# Using ggplot2 to create the dual Y-axis plot
p <- ggplot() +
geom_line(aes(x = months, y = avg_temp, group = 1), color = "blue") +
geom_line(aes(x = months, y = avg_rainfall, group = 1), color = "green", linetype="dashed") +
labs(title = "Monthly Climate Data", x = "Months", y = "Average Temperature (°C)") +
theme_minimal()
# Second Y axis for rainfall
p <- p + scale_y_continuous(sec.axis = sec_axis(~./5, name="Average Rainfall (mm)"))
print(p)
Here is what you get:
The plot will have months on the X-axis. The primary Y-axis (on the left) will track the monthly average temperature in degrees Celsius with a blue solid line, while the secondary Y-axis (on the right) will track the average monthly rainfall in millimeters with a green dashed line. The function scale_y_continuous with sec.axis argument helps us to create this secondary axis.
Please note that while dual Y-axes can make it easy to see correlations between two variables over a shared X-axis, they can sometimes be misleading or confusing, as they might give an impression of a stronger or weaker relationship between the variables than actually exists. Always use them judiciously and ensure your audience understands what they're looking at.
BridgeText can help you with all of your statistics needs.