2013-03-05 27 views
-1

我有以下表的R - 3的路表

Date Visits User 
Feb1 10  1 
Feb1 20  1 
Feb1 100 2 
Feb2 10  2 
Feb3 34  6 

我试图产生堆积柱形图,其中x轴是日期和y轴是访问次数,列由访问次数由堆叠当天的用户。这是02月01日它应该显示高度的一列= 130,其中它有两个部分,由用户2 100和30由用户1

我明白,我应该产生这种形式的表格:

  1 2 6 
Feb 1 30 100 
Feb 2  10 
Feb 3   34 

然后使用barplot功能。 R是否提供了简单的功能将第一个表格转换为第二个表格格式?任何帮助将不胜感激

回答

1

一个解决方案将使用包ggplot2这项任务。

library(ggplot2) 
#assuming that data frame is named df 
ggplot(df,aes(Date,Visits,fill=factor(User)))+geom_bar(stat="identity") 

enter image description here

0

若要获取形式您所期望的数据,你可以使用xtabs

> (temp <- xtabs(Visits ~ Date + User, SODF)) 
     User 
Date  1 2 6 
    Feb1 30 100 0 
    Feb2 0 10 0 
    Feb3 0 0 34 

您需要这个数据,然后才能与barplot使用:

barplot(t(temp), legend = TRUE, 
     col = c("skyblue", "grey", "palegreen"), 
     xlab = "Date", ylab = "Visits") 

enter image description here