It's been a while since this was asked, but I know for a fact that I will be pulling new data soon and I would like to figure out how to plot it with this technique. It looks like the people in the comments and answers had an idea of how this could be don, but I couldn't quite figure it out with what was given to me. Anyone else want to take a crack at it?
I am trying to plot multiple bar graphs with factor variables that have many levels.
First, I generate a data.frame and create a factor which I order descending by a numeric value (so that the plot will move from highest to lowest). Then, I want to generate one ggplot2 object, which in this case can be gg1. This will automatically assign a color to each of the levels and build a bar chart. I then create gg2, which is the essentially the same, but with a different ordering. However, ggplot2 automatically assigns the colors based on the value of val
. I need the colors to map to the character string name
in a way that can be re-used in multiple ggplot objects.
The problem in a nutshell is that, in the example below, only the axis tickmark values change, as opposed to the colors as well. I tried using the method here to no avail. Any ideas?
library(ggplot2)
test1 <- data.frame(name = c('a', 'b', 'c'),
val = 1:3)
test1$name <- factor(test1$name,
levels = as.character(test1$name[order(-test1$val)]))
gg1 <- ggplot(data = test1) + geom_bar(aes(x = name, y = val, fill = val))
gg1
test2 <- data.frame(name = c('a', 'b', 'c'),
val = c(3, 1, 2))
test2$name <- factor(test2$name,
levels = as.character(test2$name[order(-test2$val)]))
gg2 <- ggplot(data = test2) + geom_bar(aes(x = name, y = val, fill = val))
gg2
This is how I tried to incorporate the method suggested in the linked solution:
g <- ggplot_build(gg1)
myPalette <- unique(g$data[[1]]["fill"])[, 1]
gg3 <- ggplot(data = test2) + geom_bar(aes(x = name, y = val, fill = val)) +
scale_fill_manual(values = myPalette)
gg3