简体   繁体   English

与ggplot2 geom_bar分组的条形图是绘制比例而不是计数

[英]grouped bar plot with ggplot2 geom_bar is plotting proportions not counts

I'm trying to plot a grouped bar plot (x, y by another variable) but I'm getting a proportions graph (0-1) instead of counts, with all the bars going to 1. I'm confused because the code is seems correct (using stat identity and position dodge) 我正在尝试绘制一个分组条形图(x,y由另一个变量),但我得到一个比例图形(0-1)而不是计数,所有条形都变为1.我很困惑,因为代码似乎是正确的(使用统计身份和位置闪避)

I've tried factoring the variables, doesn't work. 我已经尝试过对变量进行分解,但是不起作用。 The data frame is in long form. 数据框格很长。

ggplot(supra.long, aes(condition, measurement, fill = MODE)) +
  geom_bar(position = 'dodge', stat = "identity") 

Got the same result when I plotted this small portion of the data: 当我绘制这一小部分数据时,得到了相同的结果:

 A tibble: 6 x 3

condition measurement MODE 
  <chr>           <dbl> <chr>

INTACT              1 US   
INTACT              0 US   
INTACT              1 US   
FT                  0 MRI  
FT                  1 MRI  
FT                  0 MRI 

I'm expecting a plot of counts on the y axis, but the bars all go to 1 on a proportion scale. 我期待y轴上的计数图,但是比例尺上的条都是1。

I'd probably either summarise the data before I plot it and use the "identity" stat. 我可能要么在绘制数据之前总结数据并使用“身份”统计数据。

library(dplyr)
condition <- c("INTACT","INTACT","INTACT","FT","FT","FT")
measurement <- c(1,0,1,0,1,0)
MODE <- c("US","US","US","MRI","MRI","MRI")
supra.long <- data.frame(condition, measurement, MODE) %>%
  group_by(condition, MODE) %>%
  summarise(count = sum(measurement))

ggplot(supra.long) +
  geom_bar(aes(x=condition, y=count, fill = MODE), position = 'dodge', stat = "identity") 

Or I would filter out the zeros and use the "count" stat. 或者我会过滤掉零并使用“计数”统计信息。

supra.long <- data.frame(condition, measurement, MODE) %>% filter(measurement > 0)
ggplot(supra.long) +
  geom_bar(aes(x=condition,fill = MODE), position = 'dodge', stat = "count") 

Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM