Can't Create Error Bar

I can create bar charts but I can't create bar charts with error bars. Could anyone help me with this. Thank you so much!

I have a dataframe that can be created by using the code below:

sport <- c("badminton", "tennis")
popularity <- c("51.47569", "51.38889")
sd <- c("0.45", "0.56")

df <- data.frame(sport, popularity, sd)

I am able to create a bar chart by using the code below:
p<- ggplot(df, aes(x=sport, y=popularity, fill=sport)) +
geom_bar(stat="identity", color="black")

Also, I want to use error bars to indicate confidence levels, so use "geom_errorbar()". The code is as below. However, I can't generate a barchart with error bars.

p<- ggplot(df2, aes(x=sport, y=popularity, fill=sport)) +
geom_bar(stat="identity", color="black",
position=position_dodge()) +
geom_errorbar(aes(ymin=popularity-sd, ymax=popularity+sd), width=5,
position=position_dodge(.9))

Thank you so much in advance.

In your example, the numeric values were entered as characters. Was that it?

library(tidyverse)

sport <- c("badminton", "tennis")
popularity <- c(51.47569, 51.38889) # as numbers instead of characters
sd <- c(0.45, 0.56) # as numbers instead of characters

df <- data.frame(sport, popularity, sd)

ggplot(df, aes(x=sport, y=popularity, fill=sport)) +
  geom_bar(stat="identity", color="black")

# using df instead of df2
ggplot(df, aes(x=sport, y=popularity, fill=sport)) +
  geom_bar(stat="identity", color="black",
  position=position_dodge()) +
  geom_errorbar(aes(ymin=popularity-sd, ymax=popularity+sd),
                width=0.5,  position=position_dodge(.9))

1 Like

Thank you so much for your help, William!

1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.