我尝试了很多事情,但是无法使镶嵌图起作用。 我从一个数据帧开始:
df = data.frame(effect = c("no","no", "yes", "yes"),
sex = c("f","m","f","m"),
n = c(8,3,8,12))
df$effect <- factor((df$effect), levels=c("yes", "no"))
df$sex <- factor(df$sex)
我尝试了ggplot:
windows(width=3.5, height=3.5 )
ggplot(df) +
geom_bar(aes(effect, fill = sex))
我尝试了另一个ggplot:
library(ggmosaic)
windows(width=3.5, height=3.5 )
ggplot(df) +
geom_mosaic(aes(x = product(effect), fill = sex)) +
labs(x = "effect", y = "number")
我尝试了另一种方法:
library("graphics")
windows(width=3.5, height=3.5 )
with(df,
mosaicplot(table(effect, sex), color=TRUE))
无论我尝试了什么,单元格中的数字在图中均未正确表示。我无法弄清楚我在做什么错...
答案 0 :(得分:1)
您需要在图的定义中包括n的值。另外,由于您要对值求和,因此geom_col()
比geom_barr()
更合适。为了使条形图填充任一区域,请在几何定义中添加position =“ fill”。
df = structure(list(effect = structure(c(2L, 2L, 1L, 1L), .Label = c("yes",
"no"), class = "factor"), sex = structure(c(1L, 2L, 1L, 2L),
.Label = c("f", "m"), class = "factor"), n = c(8, 3, 8, 12)),
row.names = c(NA, -4L), class = "data.frame")
ggplot(df, aes(effect, y=n, fill = sex)) +
geom_col(position="fill")
要更改条形的宽度,您可以尝试以下操作:
library(dplyr)
widths<-df %>% group_by(effect) %>% summarize(value=sum(n)) %>% mutate(value=value/sum(value))
ggplot(df, aes(effect, y=n, fill = sex)) +
geom_col(position="fill", width=1.8*rep(widths$value, each=2))
答案 1 :(得分:1)