Let's say I have the following mean values: In my research I assigned 0 and 1 values to no and yes responses so below are the means given a 0 to 1 scale.
| Item | Mean |
| a | 0.66 |
| b | 0.37 |
| c | 0.36 |
| d | 0.12 |
| e | 0.42 |
| f | 0.68 |
| g | 0.19 |
| h | 0.27 |
| i | 0.11 |
| j | 0.37 |
How do I create a bar graph in R where you will see the bars centered around 0.5? For means > 0.5 (e.g., item a and f), the bar is above 0.5, and, for means < 0.5, the bar is below 0.5.
I tried googling code for R but I was unsuccessful at finding what I wanted. It is possible I was using the wrong key words. I am not an expert in R so I find everything R related challenging. I don't even know how to achieve what I want given my current R experience.
Update: (see comments):
library(ggplot)
df$Deviation = df$Mean - 0.5
ggplot(df, aes(x = Item, y = Deviation)) +
geom_col(aes(fill = Deviation > 0), position = position_dodge()) +
geom_hline(yintercept = 0, linetype = "dashed", color = "black") +
scale_fill_manual(values = c("TRUE" = "cadetblue3", "FALSE" = "coral3")) +
theme_minimal() +
scale_y_continuous(limits = c(-0.5, 0.5),
breaks = seq(-0.5, 0.5, by = 0.1),
labels = function(x) sprintf("%.1f", x + 0.5)) +
theme(legend.position = "bottom")
Update after clarification (removed first answer): Just remove coor_flip()
:
library(ggplot2)
df$Deviation = df$Mean - 0.5
ggplot(df, aes(x = Item, y = Deviation)) +
geom_col(aes(fill = Deviation > 0), position = position_dodge()) +
geom_hline(yintercept = 0, linetype = "dashed", color = "black") +
scale_fill_manual(values = c("TRUE" = "cadetblue3", "FALSE" = "coral3")) +
theme_minimal()+
scale_y_continuous(labels = function(x) x + 0.5,
breaks = function(x) seq(floor(min(df$Mean)),
ceiling(max(df$Mean)), by = 0.1)) +
theme(legend.position = "bottom")