r – ggplot bars with rainbow colors

The reason why you are not seeing the bars change color with scale_color_gradientn(...) is due to two reasons:

  1. The color of the bars is mapped to the fill aesthetic, not color (outline of the bars). Therefore scale_fill_gradientn() would be appropriate.

  2. The fill aesthetic is not mapped to anything in your plot code, so the bars are not going to change color until you do.

Here, you want to assign the fill aesthetic to be mapped to the same as whatever is mapped to the x aesthetic. I don’t know the structure of your dataset, imp, so here’s an example one:


df <- data.frame(x=factor(1:45), y=1:45)

ggplot(df, aes(x=x, y=y, fill=x)) +

  # use geom_col instead of geom_bar(stat="identity")
  # show.legend=F prevents the legend from being drawn
  geom_col(show.legend = FALSE) +
  coord_flip() +
  scale_fill_manual(values = rainbow(45))

enter image description here

You can also assign values= rainbow(45, s=.6, v=.9)[sample(1:45,45)] to replicate the original plot code from OP; however, the effect will be to scramble the rainbow colors.

Read more here: Source link