图上的ggplot barplot平均值 [英] ggplot barplot mean values on graph

查看:50
本文介绍了图上的ggplot barplot平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含2个因子和1个y连续变量的条形图.Μy代码是(基于内置数据集:mtcars):

I want to create a barplot with 2 factors and 1 continuous variable for y. Μy code is (it is based on the build-in dataset: mtcars):

data(mtcars)
x=mtcars
library(ggplot2)
ggplot(x,aes(x=factor(carb), y=mpg, fill=factor(carb)))
+geom_bar(stat="summary",fun.y="mean")
+labs(title="Barplot of Average MPG per Carbon category per # of Cylinders", y="Mean MPG",x="Carbon Category")
+facet_grid(.~factor(cyl))
+geom_text(aes(label=mpg),vjust=3)

我的目标是拥有(并显示)每个碳素类别和每个气缸类别的平均MPG值.我的代码正确吗?

My goal is to have (and show) the average MPG value per carbon category, per cylinder category. Is my code correct?

主要问题是,我只想在每个条上显示平均值,而不是因子值组合的所有值.

The main problem is, I just want the mean value shown on each bar, not all values for this combination of factor values.

例如: subset(x,c(x $ carb == 3& x $ cyl == 8))返回3个不同的MPG值,该图显示了所有这三个值!

For example: subset(x,c(x$carb==3 & x$cyl==8)) returns 3 different values for MPG, and the graph shows all these three!

推荐答案

您可以尝试

library(tidyverse)
mtcars %>% 
group_by(carb, cyl) %>% 
summarise(AverageMpg = mean(mpg)) %>% 
  ggplot(aes(factor(carb), AverageMpg, label=AverageMpg, fill=factor(carb))) +
  geom_col() +
  geom_text(nudge_y = 0.5) + 
  facet_grid(~cyl, scales = "free_x", space = "free_x")

这篇关于图上的ggplot barplot平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆