I'm trying to create a color ramp to plot in ggplot2 which is dependent on factors and numbers. I'll like the color ramp to be positive above and below. In my case I want to look at dominant gender population for each point.
##Create dataframe
DF1 <- data.frame(A=c("Female","Male","Male","Female","Male","Male"),
B=c(0.2,0.5,0.4,0.8,0.1,0.5), X <- c(1,2,3,4,5,6), Y <- c(1,4,3,2,3,1))
colnames(DF1)<-c("Sex", "Ratio", "X", "Y")
A sample plot of the data using ggplot just coloured it categorically not with a colour ramp.
##Basic plot using ggplot2
ggplot() + geom_point(data=DF1, aes(X,Y,colour=A),fill=B,alpha=0.8)
I'll like to create a colour ramp which is positive both sides of zero with one side is red and the other is blue based on "Sex". The colour intensity will be dependent on the "Ratio". What is the best way to do this please?
I decided to stick with new labels with amendment to the answer by @divisan. So, the first step would be to do a trial plot to determine the number breaks and then plot properly.
I see 2 ways to do this:
The Simple Way: Set
color = Sex
and then usealpha = Ratio
to adjust color saturation.This approach is simple and doesn't require changing variables, but you get a:
Red -> Clear -> Blue
gradient instead of aRed -> White -> Blue
gradientThe Nicer Way: If you want to keep a clearer
Red -> White -> Blue
gradient, you should combineSex
andRatio
into a new variable that describes your desired colors before going intoggplot
.Sex is a
factor
, so we can convert it into anumeric
and then change it into a-1:1
scale, rather than a1:2
scale. Then we multiply it byRatio
to get a single numericsex_ratio
scale that incorporates bothSex
andRatio
.Now we can use
scale_color_gradient2
to make your blue-white-red gradient scale:If you really want
sex_ratio
to be a positive range from 0 to 1, just tweak the values and set themidpoint
of the gradient manually: