r - ggplot2 具有多个因素的连续条形图

标签 r ggplot2 bar-chart continuous

我将使用 ggplot2 包标配的钻石数据集来说明我正在寻找的内容。

我想构建一个像这样的图:

library(ggplot2)
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge")

但是,我想返回一个连续变量的平均值,而不是计数。我想返回切割和颜色并获得平均克拉数。如果我输入这段代码:

ggplot(diamonds, aes(carat, fill=cut)) + geom_bar(position="dodge")

我的输出是克拉数与切工的对比。

有人知道怎么做吗?

最佳答案

您可以获得一个新的数据框,其中 mean(carat)cutcolor 分组,然后绘制:

library(plyr)
data <- ddply(diamonds, .(cut, color), summarise, mean_carat = mean(carat))
ggplot(data, aes(color, mean_carat,fill=cut))+geom_bar(stat="identity", position="dodge")

enter image description here

如果您想要更快的解决方案,您可以使用 dplyrdata.table

使用dplyr:

library(dplyr)
data <- group_by(diamonds, cut, color)%.%summarise(mean_carat=mean(carat)) 

使用data.table:

library(data.table)
data <- data.table(diamonds)[,list(mean_carat=mean(carat)), by=c('cut', 'color')]

两者的绘图代码相同。

关于r - ggplot2 具有多个因素的连续条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22418240/

相关文章:

r - openxlsx 中的换行符

r - 如何从包含R中特殊字符和单词混合的字符串中提取标题

r - 我如何在ggplot中添加点到geom_line plot

r - stat_密度2d : removed rows containing non-finite values

r - ggplot2垂直颜色条标题右居中

javascript - D3 水平条形图精确副本

python - 带有 Bokeh vbar 图的分类 y 轴和日期时间 x 轴

r - 使用插入符号包构建模型时如何跟踪进度?

c# - 在 Windows 应用程序中使用 C# 绘制条形图

r - 在 R 中围绕多个 SQL 查询包装一个函数?