一种总是躲避直方图的方法? [英] A way to always dodge a histogram?

查看:30
本文介绍了一种总是躲避直方图的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 ggplot2,我创建了一个直方图,其中一个因子在水平轴上,另一个因子用于填充颜色,使用躲避位置.我的问题是填充因子有时只为水平因子的值取一个值,并且没有什么可以躲避条形占据整个宽度.有没有办法让它不躲闪,以便所有条宽都相同?或者等效地绘制 0?

Using ggplot2 I'm creating a histogram with a factor on the horizontal axis and another factor for the fill color, using a dodged position. My problem is that the fill factor sometimes takes only one value for a value of the horizontal factor, and with nothing to dodge the bar takes up the full width. Is there a way to make it dodge nothing so that all bar widths are the same? Or equivalently to plot the 0's?

例如

ggplot(data = mtcars, aes(x = factor(carb), fill = factor(gear))) +
geom_histogram(position = "dodge")

这个答案有几个想法.在新版本发布之前也被问到了,所以也许有什么改变?使用方面(也显示在此处)我不喜欢我的情况,尽管我想编辑数据并使用 geom_bar 可以工作,但感觉不优雅.此外,当我无论如何尝试刻面时

This answer has a couple ideas. It was also asked before the new version was released, so maybe something changed? Using facets (also shown here) I don't like for my situation, though I suppose editing the data and using geom_bar could work, but it feels inelegant. Moreover, when I tried facetting anyway

ggplot(mtcars, aes(x = factor(carb), fill = factor(gear))) +
    geom_bar() + facet_grid(~factor(carb))

我收到错误layout_base(data, cols, drop = drop) 中的错误:至少一层必须包含用于刻面的所有变量"

I get the error "Error in layout_base(data, cols, drop = drop): At least one layer must contain all variables used for facetting"

我想我可以生成一个计数数据框,然后使用 geom_bar,

I suppose I could generate a data frame of counts and then use geom_bar,

mtcounts <- ddply(subset(mtcars, select = c("carb", "gear")),
    .fun = count, .variables = c("carb", "gear"))

填写不存在 0 的级别.有谁知道这是否可行,或者是否有更好的方法?

filling out the levels that aren't present with 0's. Does anyone know if that would work or if there's a better way?

推荐答案

更新 geom_bar需要stat = "identity"

我不确定这对您来说是否为时已晚,但请参阅最近帖子的答案这里也就是说,我会按照 Joran 的建议预先计算 ggplot 调用之外的计数并使用 geom_bar.与其他帖子的答案一样,计数分两步获得:首先,使用 dcast 获得计数的交叉表;其次,melt 交叉制表.

I'm not sure if this is too late for you, but see the answer to a recent post here That is, I'd take Joran's advice to pre-calculate the counts outside the ggplot call and to use geom_bar. As with the answer to other post, the counts are obtained in two steps: first, a crosstabulation of counts is obtained using dcast; then second, melt the crosstabulation.

library(ggplot2)
library(reshape2)

dat = dcast(mtcars, factor(carb) ~ factor(gear), fun.aggregate = length)
dat.melt = melt(dat, id.vars = "factor(carb)", measure.vars = c("3", "4", "5"))
dat.melt

(p <- ggplot(dat.melt, aes(x = `factor(carb)`, y = value, fill = variable)) + 
  geom_bar(stat = "identity", position = "dodge"))

图表:

这篇关于一种总是躲避直方图的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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