I'm trying to plot 2 pieces of information on a ggplot2
plot: a surface contour and domain association. I want to have contour labels on the contour plot and a legend for the domains but when I add the direct labels to my plot I lose the domain legend. How do I force both to be displayed?
Here is some test data to show my problem:
#Generate grid
grid_fit <- expand.grid(x = seq(from=1, to=10), y = seq(from=1, to=10))
#Generate sample data
data_test <- data.frame(x = grid_fit$x,y = grid_fit$y,z = grid_fit$x * grid_fit$y)
polygons_test <- data.frame(
Domain=rep(c("Domain 1", "Domain 2"), each=3),
x = c(1, 10, 10, 1, 1, 10), y = c(1, 1, 10, 1, 10, 10))
I plot a contour plot and filled polygons for the domains in ggplot:
# Plot the contour plot and polygons on top
library(ggplot2)
plot1 <- ggplot() +
geom_contour(data=data_test,
aes(x=x, y=y, z=z,colour=..level..),
na.rm=TRUE, show.legend=F) +
geom_polygon(data=polygons_test,
aes(x=x, y=y, group=Domain, fill=Domain), alpha=0.25)
print(plot1)
I then add my labels and the legend disappears from the figure
# Print contour plot labels
library(directlabels)
plot2 <- direct.label.ggplot(plot1, "last.points")
print(plot2)
I looked through the direct.label documentation and found a function called uselegend.ggplot(p,...) but that does not change anything in the output figures.
# Use the direct.label function uselegend.ggplot to add legend to plot
plot3 <- uselegend.ggplot(plot2)
print(plot3)