Reputation: 1013
I am drawing a map with ggplot using a shape file. Then I add arcs using geom_line. The arcs are colored according to their type (oneway or twoway) and then I add nodes using geom_point. The nodes are colored according to their type (Origin, Destination, Node, Parking lot). I want to have two different legends: one for the node types and one for the arc types. Unfortunately, ggplot merges the legends and produces just one legend.
Here is the code (sorry that I can't provide a workable example. I can't send the shape files):
cityplot <- ggplot(data = s_zurich, aes(x = long, y = lat, group = id), fill = "white") +
geom_polygon(data = s_zurich, fill = "white") +
ylab("") + xlab("") +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank())
cityplot_arcs <- cityplot +
geom_line(data = allarcs, aes(x = X1, y = X2, group = Id, colour = Direction), size = 1) +
xlab("") + ylab("")
cityplot_arcs_nodes <- cityplot_arcs + geom_point(aes(x = lon, y = lat, colour = Type), shape = 15, size = 4, inherit.aes = FALSE, data = allnodes) +
theme(legend.position = "none")
Any help would be appreciated.
Upvotes: 1
Views: 1817
Reputation: 8701
Here is a possible workaround. If you can keep your geom_polygon
fill out of the aes()
call - as looks to be the case above, then you can use a filled shape for the point (21 is a circle) and set the fill attribute rather than the color in the aes()
call. See below:
mock_data<-
data.frame(x=sample(1:10,20,T),
y=sample(1:10,20,T),
direction=sample(c("1way","2way"),20,T),
type=sample(c("origin","destination","node","lot"),20,T))
ggplot(mock_data) +
geom_polygon(aes(x=c(0,12,12,0),y=c(0,0,12,12),id=c(1,1,1,1)),fill="white") +
geom_point(aes(x=x,y=y,fill=type),size=10,shape=21) +
geom_line(aes(x=x,y=y,color=direction),size=2) +
scale_fill_brewer(palette="Greens") + scale_color_brewer(palette="Set1")
Failing that, you can plot a mock legend only using ggplot()
and use grid.arrange()
to plot it next to your graph minus the default legend. Let me know in the comments if you need help with that.
Upvotes: 1