Create stacked barchart to multiple variables


i have a set of data from study participants were we asked for different kind of variables (V1, V2, V3) and got yes or no answers, which were coded as 1 or 0.

The data looks something like this:
ID V1 V2 V3 gender
P001 0 1 0 male
P002 1 0 0 female
P003 1 0 0 female

I need to create a stacked barchart which should look like the following:
y-Axis: different types of variables (v1, V2, V3)
x-Axis: number of participants that responded with yes(=1) to the variables. Females should appear as the stacked subset.


Looking forward to your replies!! :slight_smile:


I managed to recreate the example data you provided with the below code, but a "reproducible example" would be helpful! Writing dput(data) outputs something which another R user can just copy-paste into their console to get your data again. If your data is big, dput(head(data)) may be the way to go.

data = tribble(
  ~ID, ~V1, ~V2, ~V3, ~gender,
  "P001", 0, 1, 0, "male",
  "P002", 1, 0, 0, "female",
  "P003", 1, 0, 0, "female",

Here I use ggplot2 to plot your barchart, first "reshaping" your data using tidyr. This stacks the V1, V2 and V3 columns on top of each other, making them one column. From there we can use that column as the y axis, the counts as the x, and map "gender" to the fill aesthetic.

data |> 
  pivot_longer(V1:V3) |>
  ggplot(aes(y = name, x = value)) +
  geom_col(aes(fill = gender)) +
  theme_bw() + 
  labs(x = "Number", y = NULL, fill = NULL) +
  theme(legend.position = "top")

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.