2016-12-05 46 views
0

我使用ggplot來繪製2個數據集並想在左上角顯示圖例。我嘗試了一些代碼,但沒有工作。我不知道爲什麼會發生這種情況。爲什麼ggplot2圖例不顯示在圖中

ggplot(mf, aes(log10(mf[,2]),mf[,1])) 
+ ggtitle("Plot") 
+ geom_point(color = "blue") + theme(plot.margin = unit(c(1,2,1,1), "cm")) 
+ xlab("xxx") + ylab("yyy") 
+ theme(plot.title = element_text(size=18,hjust = 0.5, vjust=4)) 
+ geom_point(data=mf2,aes(log10(mf2[,2]),mf2[,1]),color="red") 
+ theme(axis.title.x = element_text(size = rel(1.3))) 
+ theme(axis.title.y = element_text(size = rel(1.3))) 
+ scale_color_discrete(name = "Dataset",labels = c("Dataset 1", "Dataset 2")) 

enter image description here

回答

0

由於沒有設置值,我用我自己的價值觀爲示範的目的。

mfdataframelogval,因爲它的列。

您需要將顏色參數放在美學內。這將導致圖例的顏色映射。之後,您可以手動縮放顏色以獲得您想要的任何顏色。

您可以使用下面的代碼來獲得所需的結果。

ggplot(mf, aes(val,log))+ 
    geom_point(aes(color = "Dataset1"))+ 
    geom_point(data=mf2,aes(color="Dataset2"))+ 
    labs(colour="Datasets",x="xxx",y="yyy")+ 
    theme(legend.position = c(0, 1),legend.justification = c(0, 1))+ 
    scale_color_manual(values = c("blue","red")) 

The Output

+0

了我在合併兩個數據集一起使用 「reshape2」 和 「融」 的另一種方法。但你的方法更優雅! –