2013-03-12 51 views
4

我已經幾乎完成了下面的圖表,但是它有一個問題。ggplot2繪製了兩個圖例

圖中的圖例繪製兩次。

下面是數據:

structure(list(Period = c("January 1997 - August 2003", "September 2003 - Jun 2005", 
"Jul 2005 - Dec 2009", "January 1997 - August 2003", "September 2003 - Jun 2005", 
"Jul 2005 - Dec 2009"), Time.Period = structure(c(1L, 3L, 2L, 
1L, 3L, 2L), .Label = c("Jan 1997 - Aug 2003", "Jul 2005 - Dec 2009", 
"Sep 2003 - Jun 2005"), class = "factor"), Variable = structure(c(2L, 
2L, 2L, 1L, 1L, 1L), .Label = c("Significant", "Zscore"), class = "factor"), 
Score = c(8.798129, 4.267268, 7.280275, 1.64, 1.64, 1.64)), .Names = c("Period", 
"Time.Period", "Variable", "Score"), class = "data.frame", row.names = c(NA, 
-6L)) 

ggplot(glomor, aes(x=Time.Period, y=Score, group=Variable, shape=Variable, color=Variable)) + 
geom_point() + 
guides(fill=FALSE) + 
scale_x_discrete(limits=c("Jan 1997 - Aug 2003","Sep 2003 - Jun 2005","Jul 2005 - Dec 2009"), expand=c(.08,0)) + 
    geom_line(aes(linetype=Variable), size=1.5) + 
    geom_point(size=4.2) + 
    scale_linetype_manual(values=c(1,3)) + 
    scale_color_manual(values=c("black", "grey40"), name="", labels=c("Signficant Z-Score", "Moran's I Z-Score")) + 
    scale_fill_discrete(name="", label=c("Signficant Z-Score", "Moran's I Z-Score")) + 
    theme_classic()+ 
    ylim(0,10) + 
    xlab("Time Periods") + 
    ylab("Moran's I Z-Score") + 
    theme(axis.title.x=element_text(size=14)) + 
    theme(axis.title.y=element_text(size=14)) + 
    theme(legend.position=c(.75, .85)) + 
    theme(legend.background = element_rect(fill="white")) + 
    theme(legend.key = element_blank()) 

有誰知道,爲什麼GGPLOT2產生兩個傳說?

+0

請使用'dput(your_data)'並粘貼輸出。 – Arun 2013-03-12 19:36:36

+1

在'scale_color'中您將縮放名稱設置爲'「」'',但對於要合併爲一個顏色和形狀比例的顏色和形狀比例,它必須相同。 – baptiste 2013-03-12 19:40:12

+0

或者我相信'guide(guide =「none」)'也會起作用嗎? – 2013-03-12 19:59:26

回答

15

您有三種美學被映射到Variable:形狀,顏色和線型。當他們擁有相同的標題和標籤時,圖例一起摺疊。您已將標題設置爲空白,併爲其指定了自定義標籤(「重要Z分數」和「Moran's I Z分數」)。您需要爲線型和形狀做到這一點,以使它們一起摺疊。

變化

scale_linetype_manual(values=c(1,3)) + 

scale_linetype_manual(values=c(1,3), name="", labels=c("Signficant Z-Score", "Moran's I Z-Score")) + 

,並添加

scale_shape_discrete(name="", label=c("Signficant Z-Score", "Moran's I Z-Score")) + 

(你也可以擺脫scale_fill_discrete的,因爲你沒有實際使用的填充審美的任何地方。 )

這給出 enter image description here

+0

非常感謝。現在看到了答案,這真的很直觀有道理。 – user1738753 2013-03-13 01:55:01