[英]R Barplot with ggplot2 - two categories with different Numeric! values
我想用ggplot創建一個特定的條形圖。 到目前為止一直很好,這是我到目前為止所得到的:
ggplot(only_savings, aes(DivisionName, Total_CR)) +
geom_bar(stat="summary", fun.y="sum")
正如您所看到的 - 有兩個部門:電氣化產品和電力研磨。 在Y軸上,我們總結了數字節省(Total_CR - 總成本降低)。 但是,我想在另外兩個部分拆分Bar:Repetitive_Savings和MDF_Savings。 所以它看起來像這樣:
這是數據:(好的,我不能發布截圖,所以我會粘貼一些行)
DivisionName Repetitive_Savings MDF_Savings Total_CR
Power Grids 86.571656 0 86.571656
Power Grids 183.461221 0 183.461221
Power Grids 2326.963118 0 2326.963118
Electrification Products 1249.323277 0 1249.323277
Electrification Products 6.849336 0 6.849336
Electrification Products 3.808845 0 3.808846
DivisionName是一個因子,其他3是數值。 我怎樣才能實現我在油漆中描繪的條形圖?
我稍微改變了你的例子,因為0的值不會為我們顯示任何東西。
only_savings <- read.table(header = TRUE, text = "
DivisionName Repetitive_Savings MDF_Savings Total_CR
'Power Grids' 86.571656 500 86.571656
'Power Grids' 183.461221 500 183.461221
'Power Grids' 2326.963118 500 2326.963118
'Electrification Products' 1249.323277 500 1249.323277
'Electrification Products' 6.849336 500 6.849336
'Electrification Products' 3.808845 500 3.808846
")
ggplot
要求事物為長形式或“整齊”形式,這意味着每個觀察應該是單獨的行,這是一個額外的列告訴使用該行是屬於重復還是MDF。 一個簡單的方法是使用tidyr
包。
我們必須使用Total過濾掉所有行,因為它們不需要繪制。
library(tidyr)
pd <- gather(only_savings, 'key', 'value', -DivisionName)
pd <- pd[pd$key != 'Total_CR', ]
現在剩下要做的就是為key
指定填充顏色。
library(ggplot2)
ggplot(pd, aes(DivisionName, value, fill = key)) +
geom_bar(stat = "summary", fun.y = "sum")
請注意,我們也可以按如下方式編寫它,其中觀察的堆疊與首先對它們求和相同。
ggplot(pd, aes(DivisionName, value, fill = key)) +
geom_bar(stat = "identity")
您要做的是引入一個分類參數,其中兩個字段Repetitive_Savings
和MDF_Savings
是組。
因此,您的數據格式不正確。
你可以用它重新格式化
test.df<- diamonds[1:100,]
test.df <- test.df[,c(2,5,6)]
test.df$total <-test.df[,2]+test.df[,3]
head(test.df)
cut depth table total
1 Ideal 61.5 55 116.5
2 Premium 59.8 61 120.8
3 Good 56.9 65 121.9
4 Premium 62.4 58 120.4
5 Good 63.3 58 121.3
6 Very Good 62.8 57 119.8
Colnames<-colnames(test.df)
NewData.list<-lapply(1:nrow(test.df),function(x){
Row<-test.df[x,]
data.frame(DivisionName=Row[,1],Values=c(Row[,2],Row[,3],Row[,4]),Categories=Colnames[c(2,3,4)])
})
NewData.df <- do.call(rbind,NewData.list)
DivisionName Values Categories
1 Ideal 61.5 depth
2 Ideal 55.0 table
3 Ideal 116.5 total
4 Premium 59.8 depth
5 Premium 61.0 table
6 Premium 120.8 total
然后情節
NewData.df$Categories<- factor(NewData.df$Categories,levels=unique(NewData.df$Categories))
NewData.df <- NewData.df[order(NewData.df$Categories),]
Plot<-ggplot(NewData.df, aes(x=DivisionName, y=Values,group=Categories)) + geom_bar(stat="identity",aes(fill=Categories),colour="#000000")
ggsave(file="Test.png",Plot)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.