Reputation: 25
I'm working on a Monte Carlo simulation that spits out a matrix with 10000 observations of 8 numeric variables. I have summarized the 8 variables using dplyr as follows:
# 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.
where the first row is the mean of each variable and the second row is the standard deviation for each variable. How would I use this summary statistics to create a bar plot with 8 bars whose height is the mean and whose error bar is the standard deviation? I'm mainly not sure how to fill out the "aes" section of the ggplot.
Thank you in advance.
Upvotes: 1
Views: 427
Reputation: 60756
as @alistaire mentioned in the comments, you're data's not really in a good shape to plot with ggplot2
... so below is an example where I set up some data the way yours is structured, use gather to pull it into columns, then join it back up. Then I plot using examples from here: http://www.sthda.com/english/wiki/ggplot2-error-bars-quick-start-guide-r-software-and-data-visualization
I hope this helps...
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
Upvotes: 1