【问题标题】:How do I create a bar plot with each variable as a bar in ggplot2?如何在 ggplot2 中创建一个将每个变量作为条形的条形图?
【发布时间】:2019-02-15 10:22:39
【问题描述】:

我正在做一个蒙特卡洛模拟,它会输出一个矩阵,其中包含 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”部分。

提前谢谢你。

【问题讨论】:

  • 你的数据是横向的;行应该是观察值,列应该是变量。用df2 &lt;- as.data.frame(t(df1))修复它

标签: r matrix ggplot2 bar-chart tibble


【解决方案1】:

正如@alistaire 在 cmets 中提到的那样,您的数据并不是很适合用ggplot2 绘制...所以下面是一个示例,我按照您的结构方式设置了一些数据,使用收集来将其拉入列中,然后将其重新连接起来。然后我使用此处的示例进行绘图: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  

【讨论】:

  • 我会试试这个并回复你。非常感谢!
猜你喜欢
  • 2019-11-28
  • 2021-07-26
  • 2019-03-20
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多