Reputation: 5324
I am trying to make a plot using several contour levels with geom_contour. Each of these levels defines a zone onto which I plot points with geom_point. My problem is that I don't manage to have on the same plot a color scale for the points and one for the levels, either the same or another.
MWE:
X <- data.frame(x1 = rnorm(1e4), x2 = rnorm(1e4))
X$z <- sqrt(rowSums(X^2))
X$level <- factor(floor(X$z))
xplot <- yplot <- c(-80:80)/10
df_plot = data.frame(expand.grid(x1=xplot, x2=yplot))
df_plot$z = sqrt(rowSums(df_plot^2))
# plot several contour
ggplot(data = df_plot, aes(x1,x2)) + geom_contour(aes(z=z, color=..level..), breaks = c(1:5))
# plot points with colors corresponding to zone
ggplot(data = X, aes(x1,x2)) + geom_point(aes(color=level))
# plot both
ggplot(data = X, aes(x1,x2)) + geom_point(aes(color=level)) +
geom_contour(data = df_plot, aes(z=z), breaks = 1:5)
On this third plot I'd like to have the levels with the same colors as the points, or at least an other color scale. I've tried to put color=
in and out aes
but it does not change anything.
thanks
Upvotes: 1
Views: 5673
Reputation: 15937
The issue here is that you are mixing a discrete and a continuous colour scale (for the points and the contours, respectively) and ggplot2 uses different defaults for the two. By making the colour scale for the contours discrete as well, you can get the same colours:
ggplot(data = X, aes(x = x1, y = x2)) + geom_point(aes(colour = level)) +
geom_contour(data = df_plot, aes(z = z, colour = factor(..level.. - 1)),
breaks = 0:5, size = 1)
Note that I have reduced the number of points and increased the thickness of the lines to make the lines better visible
Upvotes: 3
Reputation: 60522
This is a slightly long winded way of getting what you want, but you get there in the end.
ggplot(data = X, aes(x1,x2)) +
geom_point(aes(color=level)) + # Now add each contour separately.
geom_contour(data = df_plot, aes(z=z), breaks = 1, colour=rainbow(8)[1]) +
geom_contour(data = df_plot, aes(z=z), breaks = 2, colour=rainbow(8)[2]) +
scale_colour_manual(values=rainbow(8))
Upvotes: 0