我是一个ggplot2新手,有一个关于时间序列图的相当简单的问题。
我有一个数据集,其中的数据结构如下。
Area 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
MIDWEST 10 6 13 14 12 8 10 10 6 9当数据以这种格式组织时,如何生成时间序列。
使用reshape包,我可以将数据修改为如下所示:
totmidc <- melt(totmidb, id="Area")
totmidc
Area variable value
1 MIDWEST 1998 10
2 MIDWEST 1999 6
3 MIDWEST 2000 13
4 MIDWEST 2001 14
5 MIDWEST 2002 12
6 MIDWEST 2003 8
7 MIDWEST 2004 10
8 MIDWEST 2005 10
9 MIDWEST 2006 6
10 MIDWEST 2007 9然后运行以下代码以获得所需的图。
ggplot(totmidc, aes(Variable, Value)) + geom_line() + xlab("") + ylab("")但是,是否可以从第一个对象生成时间序列图,其中的列表示年份。
发布于 2011-02-12 03:26:53
ggplot2给你的错误是什么?下面的代码似乎可以在我的机器上运行:
Area <- as.numeric(unlist(strsplit("1998 1999 2000 2001 2002 2003 2004 2005 2006 2007", "\\s+")))
MIDWEST <-as.numeric(unlist(strsplit("10 6 13 14 12 8 10 10 6 9", "\\s+")))
qplot(Area, MIDWEST, geom = "line") + xlab("") + ylab("")
#Or in a dataframe
df <- data.frame(Area, MIDWEST)
qplot(Area, MIDWEST, data = df, geom = "line") + xlab("") + ylab("")您可能还想查看ggplot2网站,了解有关scale_date等人的详细信息。
发布于 2011-02-12 16:45:18
我猜“时间序列图”的意思是你想要得到一个条形图而不是折线图?
在这种情况下,只需稍微修改代码即可将正确的参数传递给geom_bar()。geom_bar的默认统计数据是stat_bin,它将在x尺度上计算类别的频率计数。对于您的数据,您希望覆盖此行为并使用stat_identity。
library(ggplot2)
# Recreate data
totmidc <- data.frame(
Area = rep("MIDWEST", 10),
variable = 1998:2007,
value = round(runif(10)*10+1)
)
# Line plot
ggplot(totmidc, aes(variable, value)) + geom_line() + xlab("") + ylab("")
# Bar plot
# Note that the parameter stat="identity" passed to geom_bar()
ggplot(totmidc, aes(x=variable, y=value)) + geom_bar(stat="identity") + xlab("") + ylab("")这将生成以下条形图:

https://stackoverflow.com/questions/4973031
复制相似问题