2016-07-29 63 views
-1

下面是我的数据集,我想绘制变量stateso7casdf随着时间的推移地块使用GGPLOT2

year states o7 cas df 
1989  151 117 35 16 
1990  150 158 27 12 
1991  150 194 43 12 
1992  150 173 38 9 
1993  151 169 35 14 
1994  153 169 23 9 
1995  153 158 22 8 
1996  153 157 18 6 
1997  153 214 18 11 
1998  154 186 17 5 
1999  154 222 16 7 
2000  155 210 20 4 
2001  154 210 19 2 
2002  155 231 17 2 
2003  155 268 18 1 
2004  155 236 16 3 
2005  155 263 19 1 
2006  155 238 17 5 
2007  155 284 16 3 
2008  155 318 20 4 
2009  155 295 18 5 
2010  155 330 20 4 
2011  155 312 16 3 

我用ggplot2包来完成

ggplot(dat, aes(year, o7)) + 
    geom_line() 

然而,我未能在同一图表中绘制其他变量。

  • 如何绘制数据中的其他变量?我如何将它们分配给 新标签(ggplot内)?

回答

2

当您想在同一ggplot中绘制几列时,主要推荐使用reshape2包中的melt函数。

# df = your example 
require(reshape2) 
df_melt = melt(df, id = "year") 

ggplot(df_melt, aes(x = year, y = value, color = variable)) + geom_point() 

enter image description here

正如mentionned由@Nathan日,列具有广泛不同的范围,使用facet_wrap可能是一种可能性:

ggplot(df_melt, aes(x = year, y = value, color = variable)) + geom_point() + 
facet_wrap(~variable, scales = "free") 

enter image description here

+0

感谢,看上去很不错。一件事:如何切换到具有不同颜色的点而不是具有不同颜色的点的线 - 我是色盲.. – FKG

+0

切换到线很容易geom_lines(),但如何让它们以不同的形状? – FKG

+0

如果您使用'geom_line'而不是'geom_point',则可以在'ggplot'对象的'aes'中添加'linetype = variable'。在'aes'中使用'shape = variable',然后使用'geom_point'将会修改点的形状。 – bVa

1

ggplot以图形层为基础。如果您要包括多个变量的所有暗算time,您将需要为每一个独特的层:

ggplot(dat, aes(x = year, y = o7)) + 
geom_line() + 
geom_line(aes(y = cas)) + 
geom_line(aes(y = df)) 

请记住,在ggplot函数的所有层(即geom_line)正试图继承aes(...)集通过ggplot(aes(...))。这种行为是由默认设置为TRUE

参数inherit.aes =因为它看起来像你的列具有广泛不同的范围可能会使用类似aes(colour = ?, shape = ?)来回地图casdf另一种选择是更好的控制。为了获得最大的视觉冲击力而玩耍的东西。