2013-01-11 105 views
-1

您可以使用ggplot2軟件包和mat矩陣中的數據創建以下barplot嗎?使用ggplot創建barplot

mat <- matrix(c(70.93,78.58,78.72,69.24,62.53,43.85,83.49,70.00,78.30,78.11,71.16,63.82,47.37,89.87),ncol=2) 
colnames(mat) <- c("Crude","Standardized") 
rownames(mat) <- 2006:2012 

library(gplots) 
library(RColorBrewer) 
my_palette <- palette(brewer.pal(7,"Set1")) 

barplot2(mat, 
main="Crude and Standardized Rates", 
xlab="Type", ylab="Rate", xlim=c(0,20), ylim=c(40,100), 
col=my_palette, beside=TRUE, plot.grid = TRUE, xpd=FALSE) 
legend(locator(1), rownames(mat), title ="Year",fill=my_palette) 

enter image description here

回答

6

這是一個非常簡單的ggplot曲線圖。其原理是將數據融入長形式,然後映射美學。然後應用啤酒調色板就是使用比例尺的問題。

library("reshape2") 

tmp <- melt(mat) 
names(tmp) <- c("Year", "Type", "Rate") 

library("ggplot2") 

ggplot(tmp, aes(x=Type, y=Rate, fill=factor(Year))) + 
    geom_bar(stat="identity", position="dodge", colour="black") + 
    scale_fill_brewer(type="qual", palette=1) 

enter image description here

編輯:

在評論,你問怎麼放大的酒吧,和@joran給予了迴應這coord_cartesian將這樣做。但我想回應他的關注。不要那樣。酒吧代表他們的面積價值;不從0開始意味着你扭曲了分歧。你可以改變的表示顯示的差異:

ggplot(tmp, aes(x=Year, y=Rate, colour=Type)) + 
    geom_point() + 
    geom_line() 

enter image description here

它使用點和線,通過在軸不包括0

+0

謝謝你這不失真位置代表了自己的價值。我的一個問題是,我無法將y軸的極限值設置爲c(40,100),就像我發佈的圖中一樣。你能告訴我該怎麼做嗎? – Brani

+0

當我給出一個「+ scale_y_continuous(限制= c(40,100))」的限制是可以的,但情節消失。 – Brani

+2

@Brani改爲使用'coord_cartesian'。但要注意的是,只有展示這些酒吧的頂部,在嚴肅的圖形專家中通常被認爲是相當不好的做法。 – joran