2017-09-30 51 views
1

我使用條形圖和線條來創建我的圖。演示代碼:使用手動形狀和顏色創建圖例

timestamp <- seq(as.Date('2010-01-01'),as.Date('2011-12-01'),by="1 mon") 
data1 <- rnorm(length(timestamp), 3000, 30) 
data2 <- rnorm(length(timestamp), 30, 3) 
df <- data.frame(timestamp, data1, data2) 

p <- ggplot() 
p <- p + geom_histogram(data=df,aes(timestamp,data1),colour="black",stat="Identity",bindwidth=10) 
p <- p + geom_line(data=df,aes(timestamp,y=data2*150),colour="red") 
p <- p + scale_y_continuous(sec.axis = sec_axis(~./150, name = "data2")) 
p <- p + scale_colour_manual(name="Parameter", labels=c("data1", "data2"), values = c('black', 'red')) 
p <- p+ scale_shape_manual(name="Parameter", labels=c("data1", "data2"), values = c(15,95)) 
p 

這導致這樣一個情節:

enter image description here

這個數字沒有一個傳奇。我遵循this答案來創建一個自定義的圖例,但它不適用於我的情況。我想在我的圖例中對應條形和線條的方形和線形。我們怎樣才能得到它?

欲圖例示於下面的圖像: enter image description here

回答

2

對於要顯示的數據的類型,是geom_bar更好的貼合,然後geom_histogram。當您操縱圖例的形象時,您需要將colour = ...部件放在aes的內部。爲了得到想要的結果,最好對線和條使用不同類型的圖例。通過這種方式,您可以更好地使用guide_legendoverride.aes更改圖例的外觀。

用於您的問題的建議:

ggplot(data = df) + 
    geom_bar(aes(x = timestamp, y = data1, colour = "black"), 
      stat = "Identity", fill = NA) + 
    geom_line(aes(x = timestamp, y = data2*150, linetype = "red"), colour = "red", size = 1) + 
    scale_y_continuous(sec.axis = sec_axis(~./150, name = "data2")) + 
    scale_linetype_manual(labels = "data2", values = "solid") + 
    scale_colour_manual(name = "Parameter\n", labels = "data1", values = "black") + 
    guides(colour = guide_legend(override.aes = list(colour = "black", size = 1), 
           order = 1), 
     linetype = guide_legend(title = NULL, 
           override.aes = list(linetype = "solid", 
                colour = "red", 
                size = 1), 
           order = 2)) + 
    theme_minimal() + 
    theme(legend.key = element_rect(fill = "white", colour = NA), 
     legend.spacing = unit(0, "lines")) 

這給:

enter image description here

+0

我仍然不能夠改變形狀的傳奇。我在我的問題中添加了預期的情節。 –

+0

@HaroonRashid查看更新HTH – Jaap