2013-03-05 20 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