我喜欢R但是简单的策划让我很生气。我有5列数据。第一列数据的日期格式为“数字”,格式为20101101,20101102等...我尝试从数字转换为日期但不起作用。
我想用col1,col2,col3和col4制作一个折线图,用x或者每个月的x轴做日期。我不希望每周或每个月都看到所有日期。你能帮忙吗?
这是我的R代码:
dates<-c(20101101,20101102,20101103,20101104,20101105,20101106,20101107,20101108,20101109,20101110,20101111,20101112,20101113,20101114,20101115,20101116,20101117,20101118,20101119,20101120) <br/>
col1<-c(seq(from=1,to=20, by=1))<br/>
col2<-c(seq(from=11,to=30, by=1))<br/>
col3<-c(seq(from=21,to=40, by=1))<br/>
col4<-c(seq(from=31,to=50, by=1))<br/>
data<-cbind(dates, col1, col2, col3, col4)<br/>
class(dates)<br/>
data #This is what my data looks like. NOTE: the "dates" field is type numeric so I TRY convert it below<br/><br/>
data[,1]<-as.Date(as.character(data[,1]), format("%Y%m%d"))#convert to date class<br/>
class(data[,1]) ### the conversion did not work. Help? The date column is still is numeric<br/>
现在我想用ggplot显示一条包含4行的线图,并在x轴上显示周或月的日期
任何帮助??
谢谢。
答案 0 :(得分:5)
正如@Dwin指出的那样,使用data.frame
而不是矩阵,因为您的转换工作正常。
e.g. class(as.Date(as.character(data[,1]), format("%Y%m%d")) )
#[1] "Date"
使用ggplot2
使用melt()
绘制您想要的数据,使用scale_x_date()
然后使用data<-data.frame(dates=dates, col1=col1, col2=col2, col3=col3, col4=col4)
library(plyr)
data <- melt(data, id.vars="dates")
data[,1]<-as.Date(as.character(data[,1]), format("%Y%m%d"))
ggplot(data, aes(x=dates,y=value)) + geom_point(aes(colour=variable)) +
scale_x_date(breaks = date_breaks("weeks"), labels = date_format("%d-%b"))
来逐行格式化。
{{1}}
答案 1 :(得分:3)
您不能将R日期与矩阵中的数字列混合使用。只能在数据框中执行:
data <- as.data.frame(data)
data$dates <- as.Date(as.character(data$dates), format="%Y%m%d")
head(data)
dates col1 col2 col3 col4
1 2010-11-01 1 11 21 31
2 2010-11-02 2 12 22 32
3 2010-11-03 3 13 23 33
4 2010-11-04 4 14 24 34
5 2010-11-05 5 15 25 35
6 2010-11-06 6 16 26 36
我从来没有“得到”ggplot的事情。似乎是graphics::matplot
的工作:
png("my.png")
matplot(x=data[[1]], y=data[-1], type="l", xaxt="n")
axis(1, at=data$dates,labels=as.character(data$dates))
dev.off()
我使用ggplot失败了:
> p <- ggplot(data=data, aes(x=dates, y=data[,2:5]) )+geom_line()
> p
Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous
Error: Aesthetics must either be length one, or the same length as the dataProblems:data[, 2:5]