changeR
changeR

Reputation: 37

How do I have to arrange the data to get this ggplot?

Suppose I have six different matrixes like this:

set.seed(999)

similarity_context_set1 = matrix(rnorm(10*3,10,1),ncol=3)
similarity_context_set2 = matrix(rnorm(10*3,10,1),ncol=3)

att_set1_prop_context_set1 = matrix(rnorm(10*3,10,1),ncol=3)
att_set1_prop_context_set2 = matrix(rnorm(10*3,10,1),ncol=3)

compromise_context_set1 = matrix(rnorm(10*3,10,1),ncol=3)
compromise_context_set2 = matrix(rnorm(10*3,10,1),ncol=3)

How do I have to arrange the data to get the following barplot with ggplot2? enter image description here

Note, the bars should represent mean values so for example, the mean value of similarity_context_set1 column 1 is the first bar (target on the image), the mean value of similarity_context_set1 column 2 is the second bar (competitor on the image) etc.

Upvotes: 0

Views: 52

Answers (1)

Roman
Roman

Reputation: 17648

You can try a tidyverse

set.seed(999)

similarity_context_set1 = matrix(rnorm(10*3,10,1),ncol=3)
similarity_context_set2 = matrix(rnorm(10*3,10,1),ncol=3)

# here I deleted the first set1 in the name
att_prop_context_set1 = matrix(rnorm(10*3,10,1),ncol=3)
att_prop_context_set2 = matrix(rnorm(10*3,10,1),ncol=3)

compromise_context_set1 = matrix(rnorm(10*3,10,1),ncol=3)
compromise_context_set2 = matrix(rnorm(10*3,10,1),ncol=3)

library(tidyverse)

# add all matrices in a list. I use lst here since the ouptut is 
# a named list 
lst(similarity_context_set1,
    similarity_context_set2,
    att_prop_context_set2,
    att_prop_context_set1,
    compromise_context_set1,
    compromise_context_set2) %>% 
  # transform to tibble and add column names
  map(as_tibble) %>% 
  map(set_names, c("Target", "Competitor", "Third")) %>% 
  # bind the list to one dataframe, add list names to column by 
  # setting .id
  bind_rows(.id = "name") %>% 
  # transform data from wide to long as it is recommended ggplot 
    input format here
  pivot_longer(-1,names_to = "x", values_to = "y") %>% 
  # make to columns for facetting
  separate(name, into = c("name1", "name2"), sep = "_", extra = "merge") %>% 
  mutate(name2 = str_extract(name2, "[0-9]")) %>% 
  # finally the plot
  ggplot(aes(x, y, group=x)) + 
  geom_bar(stat = "summary", fun = "mean")+
   facet_grid(name2~name1)

enter image description here

The errorbars can be included by adding this line

 stat_summary(fun.data = mean_se, geom = "errorbar", width=0.5)

Upvotes: 1

Related Questions