Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...