Inserting error bars on a percentage graph

I have been trying to add error bars to my ggplot with no luck. The ggplot is based on the prevalence of Cryptosporidium in two housing categories (indoor and outdoor). I would like to add error bars to the respective bars but I keep getting something like this:

Bad plot

My code looks like this:

#Housing Graph % Prevalence
yesHousingonly<-cows$Housing.Status[cows$Result == "yes"]


ggplotHousing<-ggplot(df5, aes(x = yesHousingonly, fill=yesHousingonly)) + geom_bar(aes(y = (..count..)/sum(..count..))) + theme_bw()

ggplotHousing + xlab("Housing Status") + ylab("% Prevalence") + scale_fill_brewer(name="Housing Status", labels=c("Indoor", "Outdoor"), palette = "PuRd") + scale_x_discrete(breaks=c("indoor", "outdoor"),labels=c("Indoor", "Outdoor"))

I have tried using the geom_errorbar() function but the ymin and ymax values I am inserting always end up yielding something like the above.

Thanks in advance for any help!

Here is a simple example that roughly matches your ggplot call. You do not say how you get your error bar values, so I manually entered them.

DF <- data.frame(HousingStatus = c(rep("Indoor", 3), rep("Outdoor", 7)))
DFerror <- data.frame(HousingStatus = c("Indoor", "Outdoor"),
                      Lower = c(0.2, 0.6),
                      Upper = c(0.4, 0.8))
#>   HousingStatus Lower Upper
#> 1        Indoor   0.2   0.4
#> 2       Outdoor   0.6   0.8
ggplot(DF, aes(x = HousingStatus, fill = HousingStatus)) + labs(y = "Fraction") +
  geom_bar(aes(y = (..count..)/sum(..count..))) + theme_bw() +
  geom_errorbar(aes(ymin = Lower, ymax = Upper), data = DFerror, width = 0.2)

Created on 2020-02-25 by the reprex package (v0.3.0)

Thank you so much for this, it has been really helpful!!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.