Reputation: 2715
I have dataset which has three categorical variables
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")
I used following code to generate the plot
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)
However, it does not distinguish between different types visually. Can we have different colors for different types or something to distinguish them from one another along with the legend.
Upvotes: 0
Views: 279
Reputation: 3689
While your question is not entirely clear to me, you are not using the variable type
in your plot at all, so that is one thing to change.
Now, when you have thee dimensions, you may want to facet it; separating out the data into separate panels, here using the type variable (New
subset on the left; Old
on the right):
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)
Upvotes: 4
Reputation: 98419
There could be two solutions. First, change color around bars according to 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)
Second, use interaction between Type
and Var
2 for filling.
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)
Upvotes: 3