2011-03-07 131 views
5

對於以下的數據集,繪製彙總統計

Genre Amount 
Comedy 10 
Drama 30 
Comedy 20 
Action 20 
Comedy 20 
Drama 20 

欲構建GGPLOT2線圖,其中x軸是Genre和y軸是所有量的總和(在條件Genre)。

我曾嘗試以下:

p = ggplot(test, aes(factor(Genre), Gross)) + geom_point() 
p = ggplot(test, aes(factor(Genre), Gross)) + geom_line() 
p = ggplot(test, aes(factor(Genre), sum(Gross))) + geom_line() 

,但無濟於事。

回答

8

如果你不想繪製之前,計算一個新的數據幀,你cvan使用stat_summary。例如,如果你的數據集是這樣的:

R> df <- data.frame(Genre=c("Comedy","Drama","Action","Comedy","Drama"), 
R+     Amount=c(10,30,40,10,20)) 
R> df 
    Genre Amount 
1 Comedy  10 
2 Drama  30 
3 Action  40 
4 Comedy  10 
5 Drama  20 

您可以使用qplotstat="summary"說法:

R> qplot(Genre, Amount, data=df, stat="summary", fun.y="sum") 

或者添加stat_summary到基ggplot圖文:

R> ggplot(df, aes(x=Genre, y=Amount)) + stat_summary(fun.y="sum", geom="point") 
+0

整齊的單線......儘管你可以很容易地忽略因素,因爲stringsAsFactors '是默認行爲。 – aL3xa 2011-03-07 09:25:18

+0

我想我會讓因子()指令,因爲它在問題中使用,但你是對的,在這裏沒有用。感謝您指出它。 – juba 2011-03-07 09:35:58

+0

非常感謝,我使用係數的原因是因爲我試圖將總和從低到高,但是它沒有這樣做。 – 2011-03-07 09:50:54

1

嘗試這樣:在GGPLOT2

dtf <- structure(list(Genre = structure(c(2L, 3L, 2L, 1L, 2L, 3L), .Label = c("Action", 
"Comedy", "Drama"), class = "factor"), Amount = c(10, 30, 20, 
20, 20, 20)), .Names = c("Genre", "Amount"), row.names = c(NA, 
-6L), class = "data.frame") 

library(reshape) 
library(ggplot2) 
mdtf <- melt(dtf) 
cdtf <- cast(mdtf, Genre ~ . , sum) 
ggplot(cdtf, aes(Genre, `(all)`)) + geom_bar() 
+0

您是否自動從問題提供的示例中自動生成structure()指令?如果是的話,我會很高興知道如何:-) – juba 2011-03-07 09:33:54

+0

不,我手動輸入它,因此應用了'dput'。 – aL3xa 2011-03-07 09:41:50

+0

但是,您可以使用'psych'包中的'read.clipboard'功能。它的作用就像一個魅力:'dtf < - read.clipboard()'。感謝提醒我'那回合。 – aL3xa 2011-03-07 09:56:50