R语言 在条形图中保留未使用的水平

oogrdqng  于 2023-01-06  发布在  其他
关注(0)|答案(4)|浏览(126)

我想在条形图中绘制未使用的水平(即计数为0的水平),但是,未使用的水平被删除,我不知道如何保留它们

df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5))
df$type <- factor(df$type, levels=c("A","B", "C"))

ggplot(df, aes(x=group, fill=type)) + geom_bar()

在上面的例子中,我想看到C标绘为计数0,但它完全不存在...
谢谢你的帮助尤里克
编辑:
这正是我想要的

df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5))
df1 <- data.frame(type=c("A", "A", "A", "B", "B", "A", "A", "C", "B", "B"), group=c(rep("group1", 5),rep("group2", 5)))

df$type <- factor(df$type, levels=c("A","B", "C"))
df1$type <- factor(df1$type, levels=c("A","B", "C"))
df <- data.frame(table(df))

df1 <- data.frame(table(df1))

ggplot(df, aes(x=group, y=Freq, fill=type)) + geom_bar(position="dodge")
ggplot(df1, aes(x=group, y=Freq, fill=type)) + geom_bar(position="dodge")

猜测解决方案是使用表()计算频率,然后绘制

f5emj3cl

f5emj3cl1#

您需要在两个刻度(填充和x)上设置drop = FALSE,如下所示:

library(ggplot2)
df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5))
df1 <- data.frame(type=c("A", "A", "A", "B", "B", "A", "A", "C", "B", "B"), group=c(rep("group1", 5),rep("group2", 5)))
df$type <- factor(df$type, levels=c("A","B", "C"))
df1$type <- factor(df1$type, levels=c("A","B", "C"))

plt <-  ggplot(df, aes(x=type, fill=type)) + 
          geom_bar(position='dodge') + 
          scale_fill_discrete(drop=FALSE) +
          scale_x_discrete(drop=FALSE)
plt1 <- ggplot(df1, aes(x=type, fill=type)) + 
          geom_bar(position='dodge') + 
          scale_fill_discrete(drop=FALSE) +
          scale_x_discrete(drop=FALSE)

编辑:
我很确定这是可行的。忘了把x改成type而不是group和position ='dodge '!粘贴并测试一下。stat_bin处理的是计数为零的箱子。检查docs

ctehm74n

ctehm74n2#

这是你想要的吗?

ggplot(df, aes(x=type)) + geom_bar() + scale_x_discrete(drop=FALSE)

hrysbysz

hrysbysz3#

删除级别无效。删除第一个示例中的级别

library(ggplot2)

df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5))
df$type <- factor(df$type, levels=c("A","B", "C"))

ggplot(df, aes(x=group, fill=type)) + geom_bar(position="dodge") + scale_x_discrete(drop=FALSE) + scale_fill_discrete(drop=FALSE)

此图中的结果:

解决方案在第二个示例中,其中频率是手动计算的:

df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5))
df1 <- data.frame(type=c("A", "A", "A", "B", "B", "A", "A", "C", "B", "B"), group=c(rep("group1", 5),rep("group2", 5)))

df$type <- factor(df$type, levels=c("A","B", "C"))
df1$type <- factor(df1$type, levels=c("A","B", "C"))

df <- data.frame(table(df))
df1 <- data.frame(table(df1))

df$plot = "A"
df1$plot = "B"

df <- rbind(df, df1)

ggplot(df, aes(x=group, y=Freq, fill=type)) + geom_bar(position="dodge", stat="identity") + facet_wrap( ~ plot, scales="free")

结果是:

最后一个是信息量最大的,因为空间被类别占用,计数= 0

r7knjye2

r7knjye24#

您也可以使用“scale_fill_color”,例如:

plt <- ggplot(df, aes(x=type, fill=type)) + geom_bar(position='dodge') + scale_x_discrete(drop=FALSE)+
scale_fill_manual(
  values = c(
    "#ff6666",
    "#cc9900",
    "#cc9900"
    ),drop=FALSE)

相关问题