如何减少单个柱的 geom_bar 中的 binwidth?
How to reduce binwidth in geom_bar for one single bar?
我正在尝试使用 ggplot geom_bar()
获得并排条形图。这是我为复制目的而编造的一些示例数据:
dat <- data.frame("x"=c(rep(c(1,2,3,4,5),5)),
"by"=c(NA,0,0,0,0,NA,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))
我想绘制按 "by" 分组的 "x"。现在,因为我不需要绘制 NA
值,所以我过滤了 !is.na(by)
)
library(dplyr)
dat <- filter(dat, !is.na(by))
剧情开始:
library(ggplot2)
ggplot(dat, aes(x=x, fill=as.factor(by))) + geom_bar(position="dodge") + theme_tufte()
这个returns我需要的;几乎。不幸的是,第一个条形看起来很奇怪,因为它的 binwidth 是两倍高(由于 "by" 中没有零 "x"==1)。
有没有办法将第一个柱的 binwidth 减小回 "normal"?
你也可以这样做。预先计算 table 并使用 geom_col
.
ggplot(as.data.frame(table(dat)), aes(x = x, y = Freq, fill = by)) +
theme_bw() +
geom_col(position = "dodge")
没关系,我只是发现您可以使用 ifelse
语句来操纵 binwidth
参数。
...geom_bar(..., binwidth = ifelse("by"==1 & is.na("x"), .5, 1)))
所以如果你尝试一下这个,它就会起作用。至少对我有用。
我正在尝试使用 ggplot geom_bar()
获得并排条形图。这是我为复制目的而编造的一些示例数据:
dat <- data.frame("x"=c(rep(c(1,2,3,4,5),5)),
"by"=c(NA,0,0,0,0,NA,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))
我想绘制按 "by" 分组的 "x"。现在,因为我不需要绘制 NA
值,所以我过滤了 !is.na(by)
)
library(dplyr)
dat <- filter(dat, !is.na(by))
剧情开始:
library(ggplot2)
ggplot(dat, aes(x=x, fill=as.factor(by))) + geom_bar(position="dodge") + theme_tufte()
这个returns我需要的;几乎。不幸的是,第一个条形看起来很奇怪,因为它的 binwidth 是两倍高(由于 "by" 中没有零 "x"==1)。
有没有办法将第一个柱的 binwidth 减小回 "normal"?
你也可以这样做。预先计算 table 并使用 geom_col
.
ggplot(as.data.frame(table(dat)), aes(x = x, y = Freq, fill = by)) +
theme_bw() +
geom_col(position = "dodge")
没关系,我只是发现您可以使用 ifelse
语句来操纵 binwidth
参数。
...geom_bar(..., binwidth = ifelse("by"==1 & is.na("x"), .5, 1)))
所以如果你尝试一下这个,它就会起作用。至少对我有用。