Sequence in bar plot

31 Views Asked by At

I made a geom_bar ggplot in R. It is nearly looking for what I want. The only struggling point is the sequence in the bars. If you are looking into a bar: I want to start with the most common antibiotic and finish with the least common one. For example, if you are looking for 'KAA' it would be: red - blue - orange. How could I do that?

This is the code of my plot:

ggplot(data = Antibiotica2.1) +
  aes(
    x = reorder(Specialisme, -Freq_totaal), 
    y = Frequentie,
    fill = reorder(MedicatienaamNieuw, +Frequentie)) +
  geom_bar(
    stat = "identity", 
    position = "stack") +
  ggtitle(
    label = "Antibioticagebruik per specialisme in het AZU",
    subtitle = "Aantallen uit het jaar 2022") +
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5),
    aspect.ratio = 4/3) +
  xlab("Specialisme") +
  ylab("Aantallen") +
  scale_y_continuous(breaks = seq(0, 1200, 200)) +
  labs(fill='Antibiotica') +
  scale_fill_manual(values=c("#984ea3", "#fed9a6", "#ffffb3", "#e5d8bd", "#beaed4", "#e41a1c", "#4daf4a", "#D55E00", "#0072B2")) +
  coord_flip() 

The data is looking like this:

    MedicatienaamNieuw  Specialisme Frequentie Freq_totaal   
    augmentin           KAA         5          365
    cefazoline          KAA         115        365
    ceftriaxon          KAA         1          365
    cefuroxim           KAA         1          365
    clindamicine        KAA         161        365
    metronidazol        KAA         82         365

This is the figure I already made:

enter image description here

I tried another code, which helped me really well by the sequence of the bars (the colors are ordered well), but now the x-axis is not in the right order. The part "reorder(Specialisme, -Freq_totaal) is not working anymore. Maybe it is because of the filter part above, but I couldn't solve it. Does anybody has a good idea?

bars <- map(unique(Antibiotica2.1$Specialisme)
            , ~geom_bar(stat = "identity", position = "stack"
                        , data = Antibiotica2.1 %>% filter(Specialisme == .x)))

Antibiotica2.1 %>% 
  ggplot(aes(
    x = reorder(Specialisme, -Freq_totaal), 
    y = Frequentie, 
    fill = reorder(MedicatienaamNieuw, +Frequentie))) + 
  bars +
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5),
    aspect.ratio = 4/3) +
  scale_y_continuous(breaks = seq(0, 1200, 200)) +
  ggtitle(
    label = "Antibioticagebruik per specialisme in het AZU",
    subtitle = "Aantallen uit het jaar 2022") +
  xlab("Specialisme") +
  ylab("Aantallen") +
  labs(fill = 'Antibiotica') +
  scale_fill_manual(values = c("#984ea3", "Snow 4", "#0072B2", "#e5d8bd", "#beaed4", "#4daf4a", "#e41a1c", "#D55E00", "Yellow")) +
  coord_flip()

enter image description here

0

There are 0 best solutions below