簡體   English   中英

如何在 ggplot2 中創建每個變量作為條形圖的條形圖?

[英]How do I create a bar plot with each variable as a bar in ggplot2?

我正在研究蒙特卡羅模擬,該模擬輸出一個矩陣,其中包含 8 個數值變量的 10000 個觀察值。 我使用 dplyr 總結了 8 個變量如下:

# A tibble: 2 x 8
  V1     V2     V3     V4     V5    V6     V7    V8
 <dbl>  <dbl>  <dbl>  <dbl>  <dbl> <dbl>  <dbl> <dbl>
1 29196. 12470. 6821.  5958.  22375. 6512. 10931. 2732.
2  1675.   419.   59.1   15.5  1636.  408.   858.  312.

其中第一行是每個變量的平均值,第二行是每個變量的標准差。 我將如何使用此匯總統計數據創建一個包含 8 個條形的條形圖,條形圖的高度為平均值,誤差條為標准差? 我主要不知道如何填寫 ggplot 的“aes”部分。

先感謝您。

正如@alistaire 在評論中提到的,你的數據並不是真的適合用ggplot2 ......所以下面是一個例子,我按照你的結構方式設置了一些數據,使用 gather 將其拉入列,然后加入它備份。 然后我使用這里的示例進行繪圖: http : //www.sthda.com/english/wiki/ggplot2-error-bars-quick-start-guide-r-software-and-data-visualization

我希望這有幫助...

library(tidyverse)                                         

df <- data.frame(V1=c(100, 20), V2=c(200,30), V3=c(150,15))
df                                                         
#>    V1  V2  V3
#> 1 100 200 150
#> 2  20  30  15

means <- df[1,]                                            
sds <-   df[2,]                                            

means_long <- gather(means, key='var', value='mean')       
means_long                                                 
#>   var mean
#> 1  V1  100
#> 2  V2  200
#> 3  V3  150

sds_long <- gather(sds, key='var', value='sd')             
sds_long                                                   
#>   var sd
#> 1  V1 20
#> 2  V2 30
#> 3  V3 15

sds_long %>%                                               
inner_join(means_long) ->                                  
combined_long                                              
#> Joining, by = "var"

combined_long                                              
#>   var sd mean
#> 1  V1 20  100
#> 2  V2 30  200
#> 3  V3 15  150

p <- ggplot(combined_long, aes(x=var, y=mean)) +           
geom_bar(stat="identity") +                                
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.2)   
p  

暫無
暫無

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

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