Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

r - ggplot2 bar chart gives weird y axis

I have a sample data that looks like this:

iv <- as.factor(c("x","x","x","x","y","y","y","y"))
dv <- as.numeric(as.character(c(3,35,23,53,24,34,43,23)))

When I use ggplot2, using this code:

chart <- data.frame(iv,dv)
ggplot(chart, aes(x=iv, y=dv)) + 
          geom_bar(stat = "identity")

the bar plot has y-axis that does not correspond with my dv

May I know what did I do wrong? Thank you

question from:https://stackoverflow.com/questions/65895546/ggplot2-bar-chart-gives-weird-y-axis

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The values that you see are the sum of all dv values for each iv.

tapply(dv, iv, sum)
#  x   y 
#114 124 

Maybe one of these plots is what you want.

library(ggplot2)
library(dplyr)

chart %>%
  group_by(iv) %>%
  mutate(row = row_number()) %>%
  ggplot(aes(x=iv, y=dv, fill = factor(row))) + 
  geom_col()

enter image description here

chart %>%
  group_by(iv) %>%
  mutate(row = row_number()) %>%
  ggplot(aes(x=iv, y=dv, fill = factor(row))) + 
  geom_col(position = 'dodge')

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...