-1

My data frame looks like this:

`cycle1 ( 14 teachers)` `cycle2 ( 16 teachers)` `cycle3 ( 11 teachers)`

1              7.14                    18.8                    27.3
2              14.3                     25                      27.3
3              21.4                     25                      18.2
4              14.3                     31.2                    36.4
5              21.4                     18.8                    45.5

and I would like to create a barchart which looks like this: barchart

I succeeded to do it with the barplot() function but I need to add confidence intervals, that's why I'm trying to do it with ggplot. The problem comes from my data's organization but I don't know how to solve it.

Audreygvt
  • 5
  • 1

2 Answers2

1

You can use the following code

library(tidyverse)
library(viridis)


df %>% 
  pivot_longer(cols = -id) %>% 
  ggplot(aes(x = name, y=value, fill = factor(id))) + 
  geom_col(position = position_dodge()) + 
  scale_fill_viridis(discrete = T, name = "Title") + theme_bw() + 
  scale_y_continuous(limits = c(0, max(df)+1),
                     expand = c(0, 0)) + 
  labs(x="", y="Proportion (%)") +
  theme(text = element_text(family = "serif", color = "black", size = 15))+ 
  theme(axis.text = element_text(family = "serif", color = "black", size = 12))

enter image description here

Data

df = structure(list(id = 1:5, `cycle1 (14 teachers)` = c(7.14, 14.3, 
21.4, 14.3, 21.4), `cycle2 (16 teachers)` = c(18.8, 25, 25, 31.2, 
18.8), `cycle3 (11 teachers)` = c(27.3, 27.3, 18.2, 36.4, 45.5
)), class = "data.frame", row.names = c(NA, -5L))
Community
  • 1
  • 1
UseR10085
  • 7,120
  • 3
  • 24
  • 54
0

ggplot takes as input data in the long format. You can use melt() to transform your data to the correct long format. For information how to use melt, you can use ?melt.

This will result in a 3 column table with in the first column the variable (your different cycles) and in the 2nd the values. Using your example data (simplifying the column names) this would result in the following code.

df = data.frame(id = as.character(1:5),
                cycle1 = c(7.14, 14.3, 21.4, 14.3, 21.4), 
                cycle2 = c(18.8, 25, 25, 31.2, 18.8), 
                cycle3 = c(27.3, 27.3, 18.2, 36.4, 45.5))

library(reshape2)
library(viridis)

df_melt = melt(df, id.vars=  "id")

ggplot(df_melt, aes(x = variable, y = value, fill = id)) +
  geom_col(position = position_dodge()) +
  scale_fill_viridis_d()

ljwharbers
  • 393
  • 2
  • 8
  • I used the melt function and I get a 2 column tables but in the first one the cycles 1 for example is present in 5 columns it doesn't work with ggplot, i have this error message: Erreur : stat_count() can only have an x or y aesthetic. – Audreygvt Jun 18 '20 at 10:51
  • I have edited my comment with your example data. Hopefully it's clear now. – ljwharbers Jun 18 '20 at 11:00