2

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)
jay.sf
  • 60,139
  • 8
  • 53
  • 110
Eisek
  • 31
  • 6
  • Removing the `show.legend=FALSE` works for me. – jay.sf Dec 11 '18 at 08:00
  • Thanks, that seems to work. What I don't understand is why this becomes a problem in the first place. Any advice on not getting these problems again? – Eisek Dec 11 '18 at 09:16
  • There could be something going on in your underlying data--please post a version of that data we can work with. Check out https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Ben G Dec 12 '18 at 19:34

0 Answers0