2016-01-11 136 views
0

我想在地圖上放點,但我希望圖例只顯示填充。下面的代碼顯示了我想要繪圖1的圖例,但是一個點覆蓋在plot2圖例中的填充上。我怎樣才能擺脫plot2傳說中的那一點?我想從plot1的圖例中繪製plot2。ggplot2:多邊形和點的自定義圖例

library(sp) 
library(maptools) 
library(rgeos) 
library(ggplot2) 
library(ggmap) 


# prepare a map of USA and Canada 
data(wrld_simpl) 
canada.usa <- wrld_simpl[wrld_simpl$NAME %in% c("Canada", "United States"), ] 

# fortify and add original data 
can.us <- fortify(canada.usa, region="NAME") 
can.us2 <- merge(can.us, [email protected], by.x="id", by.y="NAME") 

# first plot - legend looks perfect 
plot1 <- ggplot(can.us2, aes(x=long, y=lat, group=group, fill=id)) + geom_polygon() + 
     coord_quickmap() + theme_nothing(legend=TRUE) 
plot1 

# generate a simple set of two points 
two.pts <- data.frame(gCentroid(canada.usa, byid=TRUE)@coords) 

# add these two points to the original plot - not the legend I want 
plot2 <- plot1 
plot2 <- plot2 + geom_point(data=two.pts, aes(x=x, y=y, group=NULL, fill=NULL, size=20)) + 
     guides(size=FALSE) 
plot2 
+0

'geom_point'內使用'show_guide = FALSE'? [見這裏。](http://stackoverflow.com/questions/12746523/preventing-a-second-legend) – Axeman

+1

賓果!其實'show_guide'已被棄用。我們現在必須使用'show.legend'。所以,在'geom_point'中包含'show.legend = FALSE'給了我想要的東西。謝謝。 – user13424

+0

啊,是的,對不起,有一箇舊版本加載。 – Axeman

回答

1

使用show.legend = FALSE來壓制geom的圖例。

ggplot(mtcars, aes(mpg, hp, col = as.factor(cyl))) + 
    geom_line() + 
    geom_point(show.legend = FALSE) 

enter image description here