简体   繁体   English

我怎样才能 plot 条形图中特征的平均值?

[英]How can I plot the mean of a feature in a barplot?

I have followed barplot example:我遵循了条形图示例:

library(ggplot2)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")

g <- ggplot(df, mapping = aes(forcats::fct_infreq(sex), fill = as.factor(size))) +
  geom_bar(colour = "white") + coord_flip() + 
  geom_text(aes(label = paste0("n=", ..count..)), stat='count', 
            position = position_stack(vjust = 0.5))
g

Which gives me:这给了我:

在此处输入图像描述

What I want is the mean of the size from the Female and the Male:我想要的是女性和男性的尺寸平均值:

在此处输入图像描述

To get the mean of values by size, you could create a mean column first,要按大小获取值的平均值,您可以先创建一个mean列,

df %>% 
  group_by(sex) %>% 
  mutate(mean = mean(size)) %>% 
  ungroup() %>% 
  ggplot(aes(fct_infreq(sex))) +
  geom_bar(aes(fill = as.factor(size)), colour = "white") + 
  geom_text(aes(label = sprintf("mean = %.2f",mean)), stat="count", position = position_stack(vjust = 0.5)) +
  coord_flip()

在此处输入图像描述


Previous answer: When you set the aesthetics with aes inside the ggplot function, it will affect all future geom_ commands, but here you should not use the same aes for geom_bar and geom_text :上一个答案:当您在ggplot function 中使用aes设置美学时,它将影响所有未来的geom_命令,但在这里您不应该对geom_bargeom_text使用相同的aes

ggplot(df, aes(fct_infreq(sex))) +
  geom_bar(aes(fill = as.factor(size)), colour = "white") + 
  geom_text(aes(label = paste0("mean=", ..count..)), stat="count", position = position_stack(vjust = 0.5)) +
  coord_flip()

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

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