discipulus
discipulus

Reputation: 2715

Stacked barchart with three categorical and one numrical columns

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)

It generates a plot like enter image description here

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

Answers (2)

ako
ako

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)

enter image description here

Upvotes: 4

Didzis Elferts
Didzis Elferts

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)

enter image description here

Second, use interaction between Type and Var2 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)

enter image description here

Upvotes: 3

Related Questions