1
votes

I keep struggling with manually assigning colours to values in ggplot2. What is the easiest way to assign colours manually ignoring alphabetical order?

Here's my data frame with a colours column representing the desired colour for each Status :

    summary_count <– structure(list(Status = structure(c(4L, 6L, 1L, 5L, 2L, 3L), .Label = c("Compromise", 
"Launched", "Not yet rated", "Promise broken", "Promise kept", 
"Stuck"), class = "factor"), n = c(15L, 4L, 4L, 7L, 9L, 21L), 
    total = c(60, 60, 60, 60, 60, 60), colours = c("#B71C1C", 
    "#F57F17", "#2196F3", "#0D47A1", "#4CAF50", "#9E9E9E")), .Names = c("Status", 
"n", "total", "colours"), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

And my ggplot code:

summary_count %>%
  ggplot(aes(x = Status, y = n, fill = Status)) +
  geom_col() +
  coord_flip() +
  geom_text(aes(label = n), 
            hjust = 1.5,
            colour = "white",
            fontface = "bold",
            size = 3) +
  scale_x_discrete(limits = rev(order)) +
  scale_fill_manual(values = summary_count$colours) +
  theme_minimal() +
  theme(axis.text.x = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank(),
        legend.position = "null")

enter image description here

Promise broken should be red, Stuck should be Orange and so on...

1
Thanks for using dput, but there seems to be a syntax error, maybe a missing (. Could you doublecheck that? - Gregor Thomas
Also, to get @wibeasley suggestion to work, you need to set fill = colours in your aes call - Jake Kaupp
Data frame generated from dput should be good now. - Tdebeus
Nice scale_identity totally worked! - Tdebeus

1 Answers

1
votes

Rather than scale_fill_identity, I would recommend creating a named vector to use with scale_fill_manual. This way you don't need the color column in your data frame.

fill_colors = as.character(summary_count$colours)
names(fill_colors) = summary_count$Status

ggplot(summary_count, aes(x = Status, y = n, fill = Status)) +
  geom_col() +
  coord_flip() +
  geom_text(aes(label = n), 
            hjust = 1.5,
            colour = "white",
            fontface = "bold",
            size = 3) +
  #scale_x_discrete(limits = rev(order)) +
  scale_fill_manual(values = fill_colors) +
  theme_minimal() +
  theme(axis.text.x = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank(),
        legend.position = "null")

I commented out the scale_x_discrete line since you didn't share the order variable.