ggplot2 + 使用日期结构的X轴刻度

5

我希望你能帮助我,因为我已经迷失了方向。

我正在尝试创建一条折线图,显示几个团队一年的表现。我将这一年分成四个季度:2012年1月1日、2012年4月1日、2012年8月1日和2012年12月1日,并将csv数据框加载到R中。

     Month               Team Position
1   1/1/12       South Africa       56
2   1/1/12             Angola       85
3   1/1/12            Morocco       61
4   1/1/12 Cape Verde Islands       58
5   4/1/12       South Africa       71
6   4/1/12             Angola       78
7   4/1/12            Morocco       62
8   4/1/12 Cape Verde Islands       76
9   8/1/12       South Africa       67
10  8/1/12             Angola       85
11  8/1/12            Morocco       68
12  8/1/12 Cape Verde Islands       78
13 12/1/12       South Africa       87
14 12/1/12             Angola       84
15 12/1/12            Morocco       72
16 12/1/12 Cape Verde Islands       69

当我尝试使用ggplot2生成图表时,第四季度12/1/12不可解地移动到了第二个位置。
ggplot(groupA, aes(x=Month, y=Position, colour=Team, group=Team)) + geom_line()

我将这个绘图放入一个名为GA的变量中,以尝试使用scale_x格式化日期:

GA + scale_x_date(labels = date_format("%m/%d"))

但是我一直收到这个错误提示:
Error in structure(list(call = match.call(), aesthetics = aesthetics,  : 

无法找到函数"date_format"

如果运行以下代码:

GA + scale_x_date()

I get this error:

Error: Invalid input: date_trans works with objects of class Date only

我正在使用运行R 2.15.2的Mac OS X操作系统。请帮忙。

抱歉。我该怎么做? - Siya
@Syia,作为一种礼貌行为,您可以点赞,特别是当您接受解决方案时...这将鼓励人们下次再帮助您... - agstudy
1个回答

6

这是因为,df$Month(假设您的data.framedf),它是一个factor并且其级别以此顺序排列。

> levels(df$Month)
# [1] "1/1/12"  "12/1/12" "4/1/12"  "8/1/12" 

解决方案是重新排列您的因子级别。
df$Month <- factor(df$Month, levels=df$Month[!duplicated(df$Month)])
> levels(df$Month)
# [1] "1/1/12"  "4/1/12"  "8/1/12"  "12/1/12"

ggplot2_factor_levels

Edit: Alternate solution using strptime

# You could convert Month first:
 df$Month <- strptime(df$Month, '%m/%d/%y')

那么你的代码应该可以运行。请查看下面的图表:

ggplot2_strptime_solution


@Arun 你是如何成功读取他的数据的?当我尝试时,遇到了一些问题...使用read.table(text='..')。 - agstudy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接