Max Candocia
Max Candocia

Reputation: 4385

How do I use ggplot2 to manually assign hexadecimal colors to each data point in a plot or bar graph?

I have a data set, and one of the variables is a factored array with hexadecimal characters (e.g. '#00FF00'). One of the things I wanted to try doing is creating a bar plot with all of the different colors combined.

I tried using

cg<-ggplot(my.data,aes(x=factor(1),fill=as.character(my.color)))

followed by

cg+geom_bar()

but the only colors plotted seem to be ones from the default scale. I've tried omitting the as.character() part of the code, but it doesn't make a difference. I also have the same issue when making 2d plots with geom_point().

If I try something like

plot(my.data$var1,my.data$var2,col=as.character(my.color))

the colors are plotted the way I wanted them, although the graph doesn't look as nice as the ones in ggplot2.

Is there something obvious I'm missing, or is this beyond the scope of ggplot2?

Upvotes: 4

Views: 2835

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98439

You should add scale_fill_identity() to use color names as actual colors.

ggplot(my.data,aes(x=factor(1),fill=my.color)) +
   geom_bar()+
   scale_fill_identity()

Upvotes: 10

Related Questions