2017-09-20 183 views
0

我剛剛在圖表上使用ggplot2繪製了多條線,並且想要爲圖表添加圖例。我遵循了一些網站展示和人們在本網站上建議的一般程序,但傳說似乎並沒有顯示出來!RStudio ggplot2圖例中未顯示圖例

有人可以幫助我如何使圖例出現在此圖表中嗎?

以下是我用來製作圖表並嘗試添加一個傳說代碼:

e<-ggplot(dataset,aes(y=Index_SE)) 
e1<-e+geom_smooth(aes(x=Professionals),model=lm,colour="black",show.legend=TRUE) 
e2<-e1+geom_smooth(aes(x=Health_Social),model=lm,colour="blue",show.legend=TRUE) 
e3<-e2+geom_smooth(aes(Manufacturing),model=lm,colour="green",show.legend=TRUE) 
e4<-e3+geom_smooth(aes(Machniery_Operators),model=lm,colour="red",show.legend=TRUE) 
e5<-e4+ggtitle("Types of Employment vs Index of Socioeconomic Advantage and Disadvantage") 
e6<-e5+xlab("Profession Prevelance in LGA(%)")+ylab("Index of Socioeconomic Advantage and Disadvantage") 
final<-e6+theme(legend.position=c(35,850),legend.justification=c(35,850))+scale_colour_manual(name="Legend",values=c("Professionals"="black","Health and Social"="blue","Manufacturing"="green","Machinery Operators"="red")) 

Graph outputted from code

+0

請閱讀有關如何創建最小示例(stackoverflow.com/help/mcve)的指南,並使用'dput'的輸出理想地編輯您的問題。 你的問題是你的數據是廣泛的。它需要重新調整爲long,然後只有一個調用'geom_smooth'和'group ='參數。如果您可以發佈您的數據,那麼我們可以提供幫助。如果你這樣做,那麼圖例將自動生成 –

回答

0

正如康納爾·尼爾森評價說,從廣角轉換的格式,以長表將讓你在一行中有geom_smooth的圖例。

但是,如果由於某種原因,您確實需要保留寬格式,您可以按照示例here手動指定圖例。需要注意的是顏色必須是每個aes()通話,並匹配scale_colour_manual的值向量的名字:

ggplot(dataset, aes(y = Index_SE)) + 
    geom_smooth(aes(x = Professionals, colour = "Professionals"), model=lm) + 
    geom_smooth(aes(x = Health_Social, colour = "Health and Social"), model=lm) + 
    geom_smooth(aes(x = Manufacturing, colour = "Manufacturing"), model=lm) + 
    geom_smooth(aes(x = Machniery_Operators, colour = "Machinery Operators"), model=lm) + 
    ggtitle("Types of Employment vs Index of Socioeconomic Advantage and Disadvantage") + 
    xlab("Profession Prevelance in LGA (%)") + 
    ylab("Index of Socioeconomic Advantage and Disadvantage") + 
    theme(legend.position = c(35, 850), 
     legend.justification = c(35, 850)) + 
    scale_colour_manual(name = "Legend", 
         values = c("Professionals" = "black", 
           "Health and Social" = "blue", 
           "Manufacturing" = "green", 
           "Machinery Operators" = "red")) 

我也刪除show.legend = TRUE因爲默認情況下,傳說只要將顯示爲有被映射美學。