我的数据集有三个分类变量
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)
的图表
然而,它并没有在视觉上区分不同类型。我们可以为不同的类型或东西使用不同的颜色,以便将它们与图例区分开来。
答案 0 :(得分:4)
虽然我的问题并不完全清楚,但你根本没有在你的情节中使用变量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)
答案 1 :(得分:3)
可能有两种解决方案。首先,根据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)
其次,使用Type
和Var
2之间的互动来填充。
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)