具有三个分类列和一个数字列的堆积条形图

Stacked barchart with three categorical and one numrical columns

我的数据集包含三个分类变量

data_input <- structure(list(Var1 = structure(c(4L, 4L, 3L, 5L, 6L, 7L, 3L, 
5L, 6L, 7L, 3L, 4L, 5L, 6L, 7L, 3L, 4L, 5L, 6L, 7L),
 .Label = c("CHEER","CHOIR", "DEEP", "OVER", "PEER", "PEEN", "POST"), 
class = "factor"), 
Var2 = c("Good", "Bad", "Good", "Good", 
"Good", "Good", "Bad", "Bad", 
"Bad", "Bad", "Good", "Good", 
"Good", "Good", "Good", "Bad", 
"Bad", "Bad", "Bad", "Bad"), 
Type = c("New", 
"New", "New", "New", "New", "New", "New", "New", "New", "New", 
"Old", "Old", "Old", "Old", "Old", "Old", "Old", "Old", "Old", 
"Old"), value = c(0, 0, 4, 28, 4, 7, 8, 10, 3, 2, 36, 10, 
23, 31, 7, 19, 3, 14, 12, 4)), 
.Names = c("Var1", "Var2", "Type", "value"), 
row.names = c(NA, -20L), class = "data.frame")

我使用以下代码生成了情节

ggplot(data = data_input, aes(x = reorder(Var1, Var2), y = value)) +
geom_bar(stat = "identity", position = "stack", aes(fill = Var2)) +
labs(y = "\n Total Number of Counts", x = NULL)

它生成的情节类似于

但是,它并没有在视觉上区分不同的类型。我们可以为不同的类型使用不同的颜色或其他东西来区分它们以及图例吗?

可能有两种解决方案。首先,根据 Type.

更改条周围的颜色
ggplot(data = data_input, aes(x = reorder(Var1, Var2), y = value)) +
      geom_bar(stat = "identity", position = "stack", aes(fill = Var2,color=Type),size=1) +
      scale_color_manual(values=c("black","grey75"))+
      labs(y = "\n Total Number of Counts", x = NULL)

其次,利用TypeVar2之间的交互进行填充。

ggplot(data = data_input, aes(x = reorder(Var1, Var2), y = value)) +
      geom_bar(stat = "identity", position = "stack", aes(fill = interaction(Type,Var2))) +
      labs(y = "\n Total Number of Counts", x = NULL)

虽然我不完全清楚你的问题,但你根本没有在你的情节中使用变量 type,所以这是需要改变的一件事。

现在,当你有这些维度时,你可能想要对它进行刻面;将数据分离到单独的面板中,此处使用类型变量(左侧的 New 子集;右侧的 Old):

ggplot(data = data_input, aes(x = Var1, y = value)) +
  geom_bar(stat = "identity", position = "stack", aes(fill = Var2)) +
  facet_wrap(~Type)+
  labs(y = "\n Total Number of Counts", x = NULL)