I have been struggling to figure this out for a while. I have been attempting to add error bars to my bar graph and i’ve hit a roadblock. First, the error bars are not showing on every bar. Second, I’m not sure whats going on with the x-axis, I wanted the values to be rounded to one decimal point.
Here is the data frame and code I am working with:
# Libraries
library(ggplot2)
library(dplyr)
# Data frame
data <- data.frame(
cup_group = c(rep("Vol. of Variable = 10g", 8), rep("Vol. of Variable = 20g", 8), rep("Vol. of Variable = 40g", 8)),
volume_of_media = rep(c("Static", "Static", "Static", "Static", "Variable", "Variable", "Variable", "Variable"), 3),
DispersionRate = c(0/24, 1/23, 1/19, 0/19, 1/24, 0/24, 0/22, 0/15, 1/46, 1/41, 1/23, 0/34, 1/48, 0/43, 0/37, 0/36, 0/96, 2/89, 6/75, 2/68, 11/96, 0/82, 0/72, 1/69),
count = rep(c("Count 1", "Count 2", "Count 3", "Count 4"), 6),
PopDensity = c(24/30, 23/30, 19/30, 19/30, 24/30, 21/30, 18/30, 15/30, 46/60, 41/60, 23/40, 34/60, 48/60, 43/60, 37/60, 36/60, 96/120, 89/120, 75/120, 68/120, 96/120, 82/120, 72/120, 69/120)
)
# Data summary for mean and SD
my_sum <- data %>%
group_by(PopDensity) %>%
summarise(
n = n(),
mean = mean(DispersionRate),
sd = sd(DispersionRate),
se = sd / sqrt(n)
)
# Bar plot with error bars
barplot3 <- ggplot(my_sum, aes(x = factor(PopDensity), y = mean)) +
geom_bar(stat = "identity", position = "dodge", color = "black", fill = "turquoise") +
geom_errorbar(aes(ymin = mean - sd, ymax = mean + sd), width = 0.2) +
labs(
title = "Bar Plot of Mean Dispersion Rate by Population Density",
x = "Population Density",
y = "Mean Dispersion Rate") +
theme_minimal()
Here is the current output for barplot3 bar plot
Here is what the graph looked like before the addition of the error bars: before
I’ve tried using scale_x_discrete(limits = c("0.5","0.6","0.7","0.8))
to try to replicate the x-axis from the bar graph before the error bars were introduced, but it gave me this result instead:
result
With this error as well:
Warning message:
Removed 9 rows containing missing values or values outside the scale range
(`geom_bar()`).
Any help would be appreciated, thank you.