Home > front end >  Bars/Columns not showing up in bar plat in ggplot2
Bars/Columns not showing up in bar plat in ggplot2

Time:08-13

I am trying to make a bar graph in R, and am following code that has been successful in the past. But, for some reason the plot is only showing the error bars for the graph, and not the bars themselves.

The data pulls from the following data frame

plr_sum2 <- data_summary(plr2, varname="Ranking", 
                        groupnames="Choice")

Which includes the following data

Choice Ranking sd se Friend
0 2.98 1.27 0.08 Incorrect
1 3.67 1.26 0.08 Correct

I have tried making the graph using both the "Choice" variable and the "Friend" variable for the bars (they are synonymous) and get the same error

graph5<-ggplot(plr_sum2, aes(x=Friend, y=Ranking) )  
  geom_col(fill="lightblue")  
  theme_bw() 
  geom_errorbar( aes(x=Friend, ymin=Ranking-se, ymax=Ranking se, width=0.2), colour="black", alpha=0.9, size=0.5) 
  labs(y = "Social Preference", x = "Register Choice") 
  scale_x_discrete(breaks=c("Correct","Incorrect")) 
  scale_y_continuous(limits=c(1,5))
graph5 

When I use this code I get the warning message, "Removed 2 rows containing missing values (geom_col)" and the graph shows up with only the error bars.

CodePudding user response:

The error stems from scale_y_continuous(limits = c(1,5)): the y-range doesn't include 0, therefore the bar is not drawn. If you want your plot to start at y = 1, use coord_cartesian(ylim = c(1, 5):

require("ggplot2")
#> Loading required package: ggplot2
#> Warning: package 'ggplot2' was built under R version 4.1.3
plr_sum2 <- data.frame(choice = c(0,1),
                 Ranking = c(2.98,3.67),
                 sd = c(1.27, 1.26),
                 se = 0.08,
                 Friend = c("Incorrect", "Correct"))

ggplot(plr_sum2, aes(x=Friend, y=Ranking) )  
  geom_col(fill="lightblue")  
  theme_bw() 
  geom_errorbar( aes(x=Friend, ymin=Ranking-se, ymax=Ranking se), width=0.2, colour="black", alpha=0.9, size=0.5) 
  labs(y = "Social Preference", x = "Register Choice") 
  scale_x_discrete(breaks=c("Correct","Incorrect"))  
  coord_cartesian(ylim = c(1, 5)) 

Created on 2022-08-12 by the enter image description here

  • Related