[英]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_bar
和geom_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.