【问题标题】:How to plot a panel time series in ggplot faceted by one of the variables of the dataframe如何在 ggplot 中绘制由数据框的变量之一分面的面板时间序列
【发布时间】:2019-02-25 11:05:30
【问题描述】:

我有一个这样的数据库,

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)

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

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

请注意,每个动物的系列长度不同。对我来说,将 2008 年到 2014 年的 x 轴与 2008 年的猫和 2008 年和 2009 年的狗的缺失数据相结合是很好的。但是,当然,如果不可能实现这一点,对我来说是如果您能帮助我解决所有系列都具有相同长度(2010-2014)的情况,那就太好了。

如何在 ggplot2 中获得该图?

非常感谢您提前

【问题讨论】:

  • 请使用dput() 和您正在处理的代码分享您的数据,以便其他人可以提供帮助。在此处查看更多信息How to make a great R reproducible example?
  • 您好,Tung,非常感谢您让我知道如何改进文章的写作。因此我很抱歉,但我是新来的。这种发帖方式好吗?
  • 不用担心。现在好了

标签: r ggplot2 timeserieschart


【解决方案1】:

你可以试试这个:

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

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

【讨论】:

  • 亲爱的 Z. Lin!非常感谢您的回复,我按照您的代码进行操作,效果很好!
猜你喜欢
  • 2020-04-11
  • 1970-01-01
  • 2021-10-31
  • 2013-05-18
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多