Setting the color label and varying the color pale

2019-07-20 16:21发布

问题:

  1. Using the code below, i can set the labels for x and y axis, but can't set the label for color that is cyl here. The documentation provides no way around.

    qplot(mpg, wt, data=mtcars, colour=cyl,xlab="MPG",ylab="WT")
    

  1. How can I vary the color palette herein qplot? So, I wish to do something like in the code below:

    x <- runif(100)
    y<-runif(100)
    time<-runif(100)  
    pal <- colorRampPalette(c('white','black'))
    cols <- pal(10)[as.numeric(cut(time,breaks = 10))]
    plot(x,y,pch=19,col = cols)
    

回答1:

You can use scale_colour_continuous for both tasks.

library(ggplot2)
qplot(mpg, wt, data = mtcars, colour = cyl, xlab = "MPG", ylab = "WT") +
  scale_colour_continuous(name = "Cylinders", low = "white", high = "black")

Here, the name parameter is the label for the colour scale. The parameters low and high denote the lower and upper limits of the continuous colour scale.


If you want to specify a continuous colour scale with three colours, you can use scale_colour_gradient2:

qplot(mpg, wt, data = mtcars, colour = cyl, xlab = "MPG", ylab = "WT") +
  scale_colour_gradient2(name = "Cylinders", midpoint = median(mtcars$cyl),
                         low = "red", mid = "green", high = "black")



标签: r ggplot2