2015-07-20 117 views
3

我想设置我的图例的线型。ggplot legend中的虚线

我的数据是这样的:

VisitMonth VisitYear CaixaForum MNAC FirstDay 
    1:   01  2007   NA 7125 2007-01-01 
    2:   02  2007   NA 5345 2007-02-01 
    3:   03  2007   NA 4996 2007-03-01 
    4:   04  2007   NA 5476 2007-04-01 
    5:   05  2007   NA 6160 2007-05-01 
---             
98:   02  2015  17903 2360 2015-02-01 
99:   03  2015  30400 2930 2015-03-01 
100:   04  2015  25422 3088 2015-04-01 
101:   05  2015  10787 2130 2015-05-01 
102:   06  2015  3679 2047 2015-06-01 

我想绘制CaixaForum论坛和MNAC列的时间序列。我有以下代码:

ggplot(data = MUSEUMS, aes(x = FirstDay, y = MNAC)) + 
    geom_line(size=0.75, aes(x = FirstDay, y = MNAC, colour = "MNAC")) + 
    geom_line(size=0.75, aes(y = CaixaForum, colour = "CaixaForum"), linetype = "dashed") + 
    labs(title = "", x = "", y = "Monthly Visitors") + theme_bw() + 
    theme(legend.title = element_text(size=16, face="bold"), legend.direction = "horizontal", 
     legend.position=c(0.5, 1.05), text = element_text(size=20)) + 
    scale_colour_manual(name="Legend",values=c(MNAC="black", CaixaForum="black")) 

正如你可以看到,你不能两个线型之间的区分传说:

enter image description here

我怎么能解决吗?

我编写了其他答案在stackoverflow但他们没有奏效。

+0

您可以使用'reshape2'包中的'melt'将您的数据转换为长格式。你会得到两列“变量”和“值”。然后,您将美学改为“y = value”和“linetype = variable”。 – drmariod

+0

@drmariod ...也许你的意思是'linetype = variable',如果他们也想在图例中看到它,那么它们看起来就是这样。 – joran

+1

您缺少的更大图片是,当您将'amap()'中的数据变量映射到美学时,图例中会出现这些东西。 – joran

回答

5

你可以只需切换到两个点层使用linetype代替color,因为你没有实际使用color在任何你的图形。

它应该是这样的:

ggplot(data = MUSEUMS, aes(x = FirstDay, y = MNAC)) + 
    geom_line(size=0.75, aes(x = FirstDay, y = MNAC, linetype = "MNAC")) + 
    geom_line(size=0.75, aes(y = CaixaForum, linetype = "CaixaForum")) + 
    labs(title = "", x = "", y = "Monthly Visitors") + theme_bw() + 
    theme(legend.title = element_text(size=16, face="bold"), legend.direction = "horizontal", 
      legend.position=c(0.5, 1.05), text = element_text(size=20)) + 
    scale_linetype_manual(name="Legend",values=c(MNAC="solid", CaixaForum="dashed")) 

如果你真的想使用你现在正在使用某种原因的办法,你可以通过添加以下行,让你通过在guide_legendoverride.aes希望线您的图形:

guides(color = guide_legend(override.aes = list(linetype = c("solid", "dashed")))) 
0

我创造了一些随机数据显示解决方案...

library(reshape2) 
df <- data.frame(a=rnorm(10), b=rnorm(10), x=1:10, other_data=rnorm(10)) 
mdf <- melt(df, id.vars='x', measure.vars=c('a','b')) 
ggplot(mdf, aes(x, value, linetype=variable)) + geom_line()