user3344266
user3344266

Reputation: 69

ggplot2 fill color from data values

I want to be able to set the ggplot fill color from values stored in the data frame. The following code is 'almost' what I am trying to do, except that instead of just using fill = MyColor, I want the code to actually use the RRGGBB hex value in the MyColor field.

df = data.frame(Animals = c("Dog", "Cat", "Horse", "Giraffe"), 
            Number = c(88, 11, 107, 59),
            MyColor = c("FFFFFF", "D9FFFF", "CC80FF", "FFB5B5"))

p <- ggplot(df)
p <- p + aes(x = Animals, y = Number, fill = MyColor)
p <- p + geom_bar(stat = 'identity')
print(p)

Thanks,

Paul

Upvotes: 4

Views: 4133

Answers (1)

Pierre L
Pierre L

Reputation: 28461

ggplot(df, aes(Animals, Number, fill=Animals)) + geom_bar(stat='identity') +
  scale_fill_manual(values = df$MyColor)

enter image description here

Upvotes: 6

Related Questions