簡體   English   中英

R:具有兩個分組順序和三列數據的堆疊條形圖

[英]R: Stacked bar graph with two orders of grouping and three columns of data

我和我的同事正在嘗試創建一個堆疊的條形圖,該條形圖首先按RIL (在x軸上)分組,然后按Trt分組,其中Trt (處理)聚在一起並按顏色區分。 我們還希望通過處理Trt標記每個聚類中的每個條形圖。

堆疊的條形圖表示SW_BeforeSW_After的計算平均值(注意,樣本數據中有一個RIL ,編號206,具有多於一行的數據)。

我本來以為將數據SW_BeforeSW_After的兩列組合在一起,但是Trt的控件處理不包含SW_BeforeSW_After數據,但是必須包含在圖中。 因此, RIL為每個控制群集繪制了SW_Total的第三列數據

我對R和數據組織領域比較陌生,所以請原諒我的業余能力。

以下是我的數據的可復制示例:

data1 <- read.table (text= "Plant RIL Trt SW_Before SW_After SW_Total 
1 85 206 Early 0.380 2.27 2.65
2 88 166 Early 0 0.311 0.311
3 92 Lindo Early 0 0.663 0.633
4 94 158 Early 0.0738 0.596 0.669 
5 95 23 Early 0.0252 0.543 0.795
6 97 Lica Early 0 0.646 0.646
7 104 166 Peak 0.227 0.261 0.488
8 108 Lica Peak 0.0705 0.816 0.887
9 113 Lindo Late 0.628 0 0.628
10 115 206 Late 0.544 1.05 1.60
11 115 206 Control NA NA 1.50", sep="", header=T)    

我意識到,創建這張圖比想象的要困難得多,因此,任何幫助/指導都將倍受贊賞。

編輯:

我現在嘗試通過RILTrt繪制平均variable (包括SW_TotalSW_BeforeSW_After )的SW_After 這是我的代碼:

melted1 <- melt(data.baSW, id=c("Plant", "RIL", "Trt"))
melted1 <- subset(melted1, RIL %in% c("158", "166", "206", "23", "Licalla", "Lindo"))


melted1 %>%
  group_by(Trt, RIL, variable) %>%
  mutate(mean.SW_Total = mean(value)) %>%
  ggplot(aes(x = RIL, y = mean.SW_Total, fill = variable)) + 
  geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ Trt)

編輯2

我已經升級了代碼以響應我的編輯#1。 我相信這是正確的代碼,但驗證會很好。

melted1 %>%
  ggplot(aes(x = RIL, y = value, fill = variable)) + 
  geom_bar(stat = 'summary', position = 'stack', fun.y = "mean") + facet_grid(~ Trt)

我不確定100%是否正確解釋了您的問題,但是我認為這很接近您想要的(從此處進行調整)。

library(reshape2) # for melt
library(tidyverse)

# convert all total values to 0 except that for the control ...
data1 <- data1 %>%
mutate(SW_Total = ifelse(Trt != "Control", 0, SW_Total))

#convert to long format
melted <- melt(data1, id=c("Plant","RIL","Trt"))

ggplot(melted, aes(x = RIL, y = value, fill = variable)) + 
  geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ Trt) 

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM