Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, is there a way to color plot points on a gradient based on a range of numbers?

Tags:

r

ggplot2

I'm new to R, and I've been able to plot points, but wondering if there is a way to apply a color gradient to the scatterplot.

I have a 3 column matrix, where the first two will be used as coordinates, and the third has range of numbers between 0 and .0001. Is there a way to color the plot points based on where they fall in the range of numbers?

 x   y   z
 15  3   6e-4
 34  22  1e-10
 24  1   5e-2
 ...

plot(x, y, main= "Title", ylab = "column y", xlab = "column x", col = rgb(0,100,0,50,maxColorValue=255), pch=16) 
like image 502
Steve Avatar asked Oct 20 '12 05:10

Steve


People also ask

How do I change the color of a data point in R?

To change the color and the size of points, use the following arguments: col : color (hexadecimal color code or color name). For example, col = "blue" or col = "#4F6228" .

How do you make a color scale in R?

If we want to create a color range in R, we can use the colorRampPalette function. In the previous R code, we have defined a new function called fun_color_range, which can be used to generate color ranges from the color with the color code #1b98e0 to red. The color codes are now stored in the data object my_colors.

What is the function to give color to plot?

Finally, the function colors() lists the names of colors you can use in any plotting function. Typically, you would specify the color in a (base) plotting function via the col argument.

How do I change the color of a scatterplot in R?

The different color systems available in R have been described in detail here. To change scatter plot color according to the group, you have to specify the name of the data column containing the groups using the argument groupName . Use the argument groupColors , to specify colors by hexadecimal code or by name .


2 Answers

I'm big on the ggplot2 package, because it does a lot to encourage good plotting habits (although the syntax is a bit confusing at first):

require(ggplot2)
df <- data.frame(x=x, y=y, z=z) #ggplot2 only likes to deal with data frames
ggplot2(df, aes(x=x, y=y, colour=z) + #create the 'base layer' of the plot
  geom_point() + #represent the data with points
  scale_colour_gradient(low="black", high="green") + #you have lots of options for color mapping
  scale_x_continuous("column x") + #you can use scale_... to modify the scale in lots of other ways
  scale_y_continuous("column y") +
  ggtitle("Title") 
like image 198
Drew Steen Avatar answered Sep 23 '22 20:09

Drew Steen


How about

plot(x, y, col = gray(z/0.0001)) 

This is by gray.

like image 42
liuminzhao Avatar answered Sep 24 '22 20:09

liuminzhao