2013-04-21 75 views
1

我剛剛從Excel中來到R,對ggplot2圖表質量的優雅感到興奮。由於它們是不同的工具,因此有不同的做事方式。我必須訓練我的大腦以R(ggplot2)的方式思考。如何繪製ggplot2中的multicolum?

我想知道,如何繪製ggplot2中的多列數據。我想採取以下數據爲例:

State   Quarter 1 Quarter 2 Quarter 3 Total 
Connecticut  385   410   521   1,316 
Pennsylvania 545   416   598   1,559 
Delaware  506   515   731   1,752 
New Jersey  591   781   617   1,989 
Maryland  946   436   895   2,277 
Vermont   945   816   895   2,656 
New York  910   867   946   2,723 

Total   4,828  4,241  5,203  14,272 

問:

  1. 我可以每個季度的數據繪製一個barplot,如何繪製所有的宿舍在同一圖表?
  2. 這可能是相當Excel的方式,有沒有更好的方式來表示R中的這些數據?
+0

通常你想在GGPLOT2長格式的數據。從'reshape2'包中查看'melt'。 – 2013-04-21 00:30:22

回答

1
df <- read.csv(text="State,Quarter1,Quarter2,Quarter3,Total 
Connecticut,385, 410, 521, 1316 
Pennsylvania, 545, 416, 598, 1559 
Delaware,506, 515, 731, 1752 
New Jersey,591, 781, 617, 1989 
Maryland,946, 436, 895, 2277 
Vermont, 945, 816, 895, 2656 
New York,910, 867, 946, 2723 
", header=T) 

library(reshape2) 

df <- melt(df, variable.name="Quarter") 

library(ggplot2) 

ggplot(df[df$Quarter != "Total",]) + 
geom_bar(aes(State, value, fill = Quarter), stat="identity") 

這產生如下圖所示:

enter image description here

1

正如註釋的建議,第一melt數據幀:

require(reshape2) 
require(ggplot2) 

data = read.table(text=" 
State, Quarter1, Quarter2, Quarter3, Total 
Connecticut,  385,   410,   521,   1316 
Pennsylvania, 545,   416,   598,   1559 
Delaware,  506,   515,   731,   1752 
New Jersey,  591,   781,   617,   1989 
Maryland,  946,   436,   895,  2277 
Vermont,   945,   816,   895,   2656 
New York,  910,   867,   946,   2723 
Total,   4828,  4241,  5203,  14272",header=T,sep=',') 

data.new <- melt(head(data,-1)) 

現在對於堆疊條形圖:

ggplot(head(data.new,-1), aes(State,value,fill=variable)) + geom_bar(position="dodge") 

enter image description here

對於並排側欄情節:

ggplot(head(data.new,-1), aes(State,value,fill=variable)) + geom_bar() 

enter image description here

+0

你不認爲把總數(特別是在堆疊位置)也是完全沒有意義的。 (在這裏是三個)堆積列的最終高度已經代表總數... – Michele 2013-04-22 13:22:55