rggplot2

ggplot geom_point color based on both x and y axis values


I have a tab delimited file like this:

variable    value   value.1
120         20      0.001
207         39      0.004
1400        56      0.007
1505        5       0.045

How is it possible to color all points under 0.005 from value.1 in grey, while all the rest take the color of orange or blue based on value? This is my code:

someplot <- ggplot(my_data, aes(x = as.numeric(levels(variable))[variable], y = value.1)) + 
geom_point(aes(colour=cut(value, c(-Inf,40,Inf))), size = 1) +
scale_color_manual(name = "age",
                 values = c("(-Inf,40]" = "orange",
                            "(40, Inf]" = "blue"),
                 labels = c("<40", ">40")) +
scale_x_continuous(limits = c(0, 16600), breaks = seq(0, 16600, by = 200)) +
scale_y_continuous(limits = c(0.001, 0.95), breaks=c(0.001, 0.005, 0.010, 0.015, 0.020, 0.040,0.060, 0.080)) +
theme(plot.title = element_text(hjust = 0.5, size=20)) +
theme(axis.text.x=element_text(size=rel(1), angle=90)) +
theme(legend.key.size = unit(1, 'cm'),
    legend.key.height = unit(1, 'cm'), 
    legend.key.width = unit(1, 'cm'), 
    legend.title = element_text(size=14),
    legend.text = element_text(size=14))
plot(someplot)

Solution

  • Create another variable for colors and set the corresponding values:

    my_data$colors <- 1 
    my_data$colors[my_data$value>40] <- 2
    my_data$colors[my_data$value.1<0.005] <- 3
    someplot <- ggplot(my_data, aes(x = variable, y = value.1)) +
    geom_point(aes(colour=as.factor(colors))) +
    scale_color_manual(name = "age",
                         values = c("1" = "orange",
                                    "2" = "blue",
                                    "3" = "gray"),
                         labels = c("<40", ">40","<0.005")) +
    scale_x_continuous(limits = c(0, 16600), breaks = seq(0, 16600, by = 200)) +
    scale_y_continuous(limits = c(0.001, 0.95), breaks=c(0.001,0.005, 0.010, 0.015, 0.020, 0.040,0.060, 0.080)) +
    theme(plot.title = element_text(hjust = 0.5, size=20)) +
    theme(axis.text.x=element_text(size=rel(1), angle=90)) +
    theme(legend.key.size = unit(1, 'cm'),
            legend.key.height = unit(1, 'cm'), 
            legend.key.width = unit(1, 'cm'), 
            legend.title = element_text(size=14),
            legend.text = element_text(size=14)) 
    plot(someplot)
    

    enter image description here