I have 80+ patients data with almost 5-6 categories assign to them within 200-300 days. So each patient has 300 days and the status name of each day. I want to make a stacked bar plot.
Problem: The problem is the ggplot sorting the categories alphabetically, I want to sort them exactly like it has in the source ALSO if for patient 1, on day 5th the category is "Medical Appointment" and the same category is repeating on day 50, ggplot does not differentiate it and takes all in one. I would like to plot on the day 50th with the "Medical Appointment" as well on the day 5th.
I counted the frequency for each patient's category. This is what I have so far:
tibble: 72 x 3
Category `Patient Number` n
<fct> <chr> <int>
1 AD Patient 1 34
2 AD Patient 2 15
3 Admin delay Patient 2 30
4 CC Patient 2 20
5 CD Patient 1 52
6 CD Patient 2 88
7 CP Patient 1 52
8 CP10 Patient 1 1
9 CP11 Patient 1 1
10 CP12 Patient 1 1
I want to plot them into a staked bar chart on the x axis it should be Patient number on y axis should be N(Count) with respective category and it should not be sorted. I have 87 patients number.
Patient and category for each day:
ggplot(data = df, aes(x = `Patient Number`, y = n, fill = as.factor(Category))) +
geom_bar(position = position_stack(reverse = TRUE), stat="identity", na.rm = FALSE) +
scale_fill_discrete(breaks = Category)
Thanks in advance. I'd appreciate if anybody could solve this.
Edit:
Here is the plot image what you @pieterbons have suggested me: