-1

I have tried to re-order my barplot to be presented in numerical order equivalent to the datasheet but the plot print in alphabetic order. I tried as.factor but it does not seem to work.

#Load data
d <- structure(list(author = structure(c(1L, 2L, 4L, 3L, 5L, 6L, 8L, 11L, 13L, 12L, 10L, 9L, 7L), .Label = c("Bahr et al", "Fuller et al", "Garbossa et al", "Gokhale et al", "Iuchi et al", "Lee et al", "Lee Y et all", "Merrel et al", "Newton et al", "Rossetti et al", "Usery et al", "Wychowski et al", "Zachenhofer et al"), class = "factor"), nAE = c(-22L, -34L, -158L, -90L, -70L, -41L, -48L, -32L, -73L, -23L, -25L, -13L, -46L), AE = c(3L, 1L, 7L, 1L, 3L, 10L, 3L, 6L, 3L, 5L, 4L, 6L, 5L), SAE = c(0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 2L, 0L, 2L, 0L, 0L)), .Names = c("author", "nAE", "AE", "SAE"), class = "data.frame", row.names = c(NA, -13L))

Code to my barplot:

library(dplyr)
library(tidyr)
library(ggplot2)

categories <- c("Adverse Effect", "No adverse effects", "Severe side 
effects")
cols <- c("#f6766d", "#01bfc4", "orange")



y <- min(d$nAE) + 10
textaes <- data.frame(y = c(y, y, y),
                  x = c(2, 7, 12),
                  lab = c("Text1", "Text2", "Text3"))
q <- d %>% 
gather(key, value, -author) %>% 
ggplot(aes(x=author, y=value, fill = key)) +
geom_col(alpha=0.9) + 
scale_x_discrete(name="Author") +
scale_y_continuous(name="Number of observations", limits=c(-160,15), 
                 seq(-160, 15, by=10), expand = c(0.15, 0.05)) +
theme_grey() +
theme(legend.position = "top",
    axis.text.x = element_text(angle = 90, hjust = 1)) +
scale_fill_manual(labels = categories, values = cols) + 
labs(fill = "") +
geom_vline(xintercept= 3.5, colour = "red") + 
geom_vline(xintercept= 10.5, colour = "red") +
geom_text(mapping = aes(y = y, x = x, label = lab), 
        data = textaes, inherit.aes = FALSE)
q

Can you help?

Thanks in advance, C.

cmirian
  • 2,572
  • 3
  • 19
  • 59

1 Answers1

1

When you use as.factor(), the levels will be determined in alphabetical order. In order to prevent that and choose your own ordering, you can specify the factor levels as follows:

d$author=factor(d$author,levels=d$author)

enter image description here

Hope this helps!

Florian
  • 24,425
  • 4
  • 49
  • 80
  • Thank you! Oh, another quick question. Do you know how to switch around the blue-ish "No adverse effect" and orange "Severe adverse effect" text around in the top legend? :) But the color equivalent to the title should remain the same – cmirian Jan 28 '18 at 21:20
  • 1
    No problem. I think you can do that by switching around the first and second values in the `cols` vector. – Florian Jan 28 '18 at 21:26