2017-02-20 74 views
-1

我一直在試圖繪製兩條線條圖,一條虛線,另一條固體。我在劇情區成功地做到了這一點,但傳說有問題。ggplot2更改線條類型

我看了帖子,如Changing the line type in the ggplot legend,但我似乎無法修復該解決方案。我哪裏錯了?

library(ggplot2) 
year <- 2005:2015 
variablea <- 1000:1010 
variableb <- 1010:1020 
df = data.frame(year, variablea, variableb) 

p <- ggplot(df, aes(x = df$year)) + 
    geom_line(aes(y = df$variablea, colour="variablea", linetype="longdash")) + 
    geom_line(aes(y = df$variableb, colour="variableb")) + 
    xlab("Year") + 
    ylab("Value") + 
    scale_colour_manual("", breaks=c("variablea", "variableb") 
         , values=c("variablea"="red", "variableb"="blue")) + 
    scale_linetype_manual("", breaks=c("variablea", "variableb") 
         , values=c("longdash", "solid")) 

p 

enter image description here

注意,兩行顯示在圖例中,爲固體。

+0

用'tidyr :: gather'將數據整形成一列,然後它就會正常工作 –

回答

2

ggplot喜歡長數據,所以你可以將線型和顏色映射到一個變量。例如,

library(tidyverse) 

df %>% gather(variable, value, -year) %>% 
    ggplot(aes(x = year, y = value, colour = variable, linetype = variable)) + 
    geom_line() 

調整顏色和線型比例與相應的scale_*_*功能,如果你喜歡。

+0

太好了。我怎樣才能確保只顯示整數年? – wwl

+1

使用'scale_x_continuous(breaks = seq(2005,2015,5))',傳遞你想要的任何休息順序。 – alistaire