son.ra
son.ra

Reputation: 55

Changing Individual Color Points in R ggplot2

I want to change the colors of a dotplot to fade depending on a cumulative probability. I am using hsv to get a list of color codes I want for each individual data point. However, I am having trouble assigning these colors to the plot. Anything so far I have found on the web has been for assigning colors based on groups.

Here is the example:

library(data.table)
library(ggplot2)

#sample of cumulative probabilities
wave <- data.table(
c(1, 1, .9, .6, .2, .02, 0, 0),
c(1, 1, 1, .8, .6, .42, .1, 0), 
c(1, 1, 1, .9, .7, .4, .34, .1))

#set up for dot plot 
dot <- data.table(rep(c(1:NROW(wave)), NCOL(wave)), 
              rep(colnames(wave), each = NROW(wave)))


#trying to use saturation in hsv to get prob dependent color fades
fade <- hsv( .9, rev(as.matrix(wave)), .55) 


 p<-ggplot(
     dot, aes(x=V2, y=V1)) + 
     geom_dotplot(binaxis='y', stackdir='center', 
          stackratio= .1, dotsize=.7
                      )


#  The following lines don't work:

p+scale_colour_manual(values = fade)
p
p+scale_fill_manual(values = fade)
p

Any help will be appreciated! Thank you.

Upvotes: 1

Views: 990

Answers (1)

august
august

Reputation: 747

If I understand you correctly, for each dot you have an associated color, which is stored in its own vector fade, and you want to plot the dots in such a way that each dot is filled in with the associated color.

In that case:

names(fade)<-fade
ggplot(dot,aes(x=V2,y=V1,fill=fade))
   +geom_dotplot(binaxis='y',stackdir='center',stackratio=.1,dotsize=.7)
   +scale_fill_manual(values=fade)

enter image description here

Essentially this sets your grouping variable as the hex colors.

Note that you could do this with geom_point pretty easily as well:

dot$probability<-do.call(c,wave)
ggplot(dot,aes(x=V2,y=V1,color=probability))
    +geom_point(size=3)
    +scale_color_gradient(low="#8C0054",high="#8C8C8C")

enter image description here

Upvotes: 1

Related Questions