Ryan Coots
Ryan Coots

Reputation: 41

How to add a "Total" to categorical variables barchart?

I have a data set that has two categorical variables. I am going to summarize the data by having one of these categorical variables on the x-axis, and the counts of the other variable as bars on the y-axis.

Is there an easy way to collapse all of the x-axis variables to a "Total" that can be appended to the figure? Something like this:

enter image description here

I should mention that this will be a stacked bar chart and have three "totals", one for each categorical response.

Upvotes: 0

Views: 52

Answers (1)

akrun
akrun

Reputation: 887731

If it is a table output, then we can use addmargins

barplot(t(addmargins(table(v1, v2), 1)))

data

set.seed(24)
v1 <- sample(c("Man", "Woman", "Legal Person", "Physical Person"), 
        100, replace = TRUE)
v2 <-  sample(1:4, 100, replace = TRUE)

Upvotes: 1

Related Questions