如何在ggplot中绘制由数据帧的变量之一构成的面板时间序列

时间:2018-09-21 05:05:40

标签: r ggplot2 timeserieschart

我有一个这样的数据库,

ani <- structure(list(year = c(2009L, 2010L, 2011L, 2012L, 2013L, 2014L, 
                               2010L, 2011L, 2012L, 2013L, 2014L, 2008L, 
                               2009L, 2010L, 2011L, 2012L, 2013L, 2014L), 
                      animal = c("cat", "cat", "cat", "cat", "cat", "cat", 
                                 "dog", "dog", "dog", "dog", "dog", "rat", 
                                 "rat", "rat", "rat", "rat", "rat", "rat"), 
                      height = c(12.5, 20, 25, 26, 28, 31, 32, 34, 37, 
                                 44, 44, 4, 5, 5, 6, 8, 8, 9), 
                      weight = c(2.4, 2.6, 2.7, 2.8, 3.2, 4.4, 4.7, 5.1, 
                                 5.6, 5.8, 6.5, 0.4, 0.5, 0.9, 1.2, 1.1, 1.3, 1.4)),
                 .Names = c("year", "animal", "height", "weight"), 
                 class = "data.frame", 
                 row.names = c(NA, -18L))

我能够以这种方式获得每只动物的身高和体重的时间序列聊天记录(在这里我是为猫做的):

cat<- subset(ani, animal == "cat")
cat[2]<-NULL # I need to delete the column of the type of animal 

这完全违背了我按照动物类型制作多重面板图的最终目标,但这是我发现绘制多个时间序列的唯一方法。

library(reshape2)
library(ggplot2)

meltcat <- melt(cat,id="year")
chartcat <- ggplot(data = meltcat, aes(x = year, y = value, colour=variable)) + geom_line()
print(chartcat)

但是,我找不到使用变量“ animal”按行创建三个级别(构面)单个图表的方法。

比方说,我想在最下面一行绘制猫的身高和体重的时间序列(从2009年到2014年)。在中间一行,我想绘制狗身高和体重的时间序列(从2010年到2014年)。在最高的一行中,我想绘制大鼠身高和体重的时间序列(从2008年到2014年)。然后,每个面板将有两个系列(高度和重量)。

请注意,每只动物的系列长度不同。对我来说,最好使用2008年至2014年的x轴,其中缺少2008年的猫以及2008年和2009年的狗的数据。但是,当然,如果不可能做到这一点,对我来说如果您能在所有系列的长度都相同(2010-2014年)的情况下为我提供帮助,那就太好了。

如何在ggplot2中获取该图?

非常感谢您

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

# reshape dataframe
meltani <- melt(ani, id.vars = c("year", "animal"))

# reverse factor order for animal (otherwise the order would be cat -> dog -> rat)
meltani$animal <- factor(meltani$animal, 
                         levels = sort(unique(meltani$animal), decreasing = TRUE))

ggplot(meltani,
       aes(x = year, y = value, colour = variable)) +
  geom_line() +
  facet_wrap(~ animal, ncol = 1)

08 - 14 plot

如果要限制所有构面的x轴范围,请在代码中添加+ coord_cartesian(xlim = c(2010, 2014))。另外,您可以通过在scales = "free_x"内添加facet_wrap()来改变各个构面的x轴范围。