Reputation: 352
I have two dataframes that give temperatures for two different times for the same set of coordinates. I'd like to plot the two together using the same color for the same temperature between the two plots; that is, I'd like to have one legend for the two plots that takes into account the fact that the range of temperatures for the two plots is not the same.
I thought that I might be able to use scale_colour_manual()
, but I'm not sure how to implement it in this case where I essentially have continuous variables (my real data have tens of thousands of observations). Here is an example of what I have so far:
# Create sample data
dat1 <- data.frame(c(-158.28, -158.27, -158.26),
c(21.57, 21.56, 21.57), c(24, 22, 25))
names(dat1) <- c('x', 'y', 'Temp.')
dat2 <- data.frame(c(-158.28, -158.27, -158.26),
c(21.57, 21.56, 21.57), c(22, 20, 23))
names(dat2) <- c('x', 'y', 'Temp.')
# Create plots
plot1 <- ggplot(dat1, aes(x,y)) + geom_point(aes(color = Temp.)) +
scale_colour_gradientn(colours = rev(rainbow(4))) +
theme(
title = element_text('January 1, 1990 at 00:00'),
legend.position = 'none') +
ggtitle('Jan. 1, 1990 00:00')
plot2 <- ggplot(dat2, aes(x,y)) + geom_point(aes(color = Temp.)) +
scale_colour_gradientn(colours = rev(rainbow(4))) + theme(
title = element_text('August 18, 2007 at 02:00'),
legend.position = 'none') +
ggtitle('Aug. 18, 2007 14:00')
# Combine plots
grid.arrange(plot1, plot2, ncol = 2, nrow = 1, respect = T)
I'd like to change the color scale so that it is relative to the combined temperatures of the two figures, not the individual figures. This code won't work, but it shows what I'm looking to do:
scale_colour_gradientn(colours = rev(rainbow(4,
start = min(c(dat1$Temp.,dat2$Temp.)),
end = max(c(dat1$Temp.,dat2$Temp.)))))
Upvotes: 3
Views: 1859
Reputation: 27339
In ggplot2, things like this get a lot easier when you make a single plot with multiple facets - try this:
# Add identifiers to each set
dat1$dtime <- 'Jan. 1, 1990 00:00'
dat2$dtime <- 'Aug. 18, 2007 14:00'
# Stack them
dat_all <- rbind(dat1, dat2)
# Plot all at once
ggplot(dat_all, aes(x = x, y = y, color = `Temp.`)) +
geom_point() +
facet_wrap( ~ dtime) +
scale_colour_gradientn(colours = rev(rainbow(4)))
Upvotes: 4