Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用ggplot2打印_R_Plot_Ggplot2 - Fatal编程技术网

R 使用ggplot2打印

R 使用ggplot2打印,r,plot,ggplot2,R,Plot,Ggplot2,下面是我的数据集,我想绘制随时间变化的变量状态,o7,cas,和df 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 19

下面是我的数据集,我想绘制随时间变化的变量
状态
o7
cas
,和
df

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内)

ggplot
以图形层为基础。如果要包含多个变量(所有变量均根据
时间绘制)
,则每个变量都需要一个唯一的图层:

 ggplot(dat, aes(x = year, y = o7)) +
 geom_line() +
 geom_line(aes(y = cas)) +
 geom_line(aes(y = df))
请记住,ggplot函数(即
geom_line
)中的所有层都试图继承
ggplot(aes(…)
设置的
aes(…)
。此行为由参数
inherit.aes=
控制,该参数默认设置为
TRUE


因为看起来您的列的范围大不相同,所以您最好使用另一个选项,例如
aes(color=?,shape=?)
fromap
cas
df
。可以发挥最大视觉效果的功能。

当您要在同一个ggplot中绘制多个列时,主要建议使用
重塑2
软件包中的
熔化
功能

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

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

正如@Nathan Day所提到的,列的范围大不相同,可以使用
facet\u wrap

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

谢谢,看起来很棒。一件事:如何切换到具有不同形状的线条而不是具有不同颜色的点–我是色盲..切换到线条很简单geom_lines(),但是如何使它们具有不同的形状呢?如果使用
geom_line
而不是
geom_point
,则可以在
ggplot
对象的
aes
中添加
linetype=variable
。在
aes
中使用
shape=variable
,然后使用
geom_point
将修改点的形状。