2017-02-20 9 views
-1

私は、折れ線グラフと破線グラフの2つの線グラフをプロットしようとしています。プロット領域では成功しましたが、伝説には問題があります。ggplot2 change line type

私は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'で再整理してデータを1つの列に入れると、それはうまくいくでしょう –

答えて

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