Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting points with color and shape based on data variables

I am trying to make a scatter plot with the colors of each point corresponding to one variable and the shape of each point corresponding to another variable. Here is some example data and the code I used to make the second plot:

Example data:(of 3 points)
 X    Y    att1    att2

.5    .5    1       A
.24   .8    3       B
.6    .7    5       C

code:(for image2)
> plot(X,Y, col=statc[att2], pch = 15)
> legend("right", statv, fill=statc)

Where:
> statv
[1] "A"  "B" "C"  
> statc
[1] "red"    "blue"   "orange"

I have done this individually but dont know how to do both. Here is two plots:

1enter image description here

2enter image description here

For example: I want the colors to apply to the points with the same att1 and the shapes to apply to points with the same att2

like image 674
Nitro Avatar asked Dec 06 '13 01:12

Nitro


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 I color a scatterplot with a variable in R?

One of the ways to add color to scatter plot by a variable is to use color argument inside global aes() function with the variable we want to color with. In this scatter plot we color the points by the origin airport using color=origin. The color argument has added colors to scatterplot with default colors by ggplot2.

How do you plot a color?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument. See also the plot command's documentation.


2 Answers

One of the domain where ggplot2 excels , comparing to other R system plots, is mapping plot parameters to data variables.( via aesthetics mechanism)

library(ggplot2)
dat <- data.frame(X =runif(20),
                     Y =runif(20),
                     att1 = gl(5,20/5),
                     att2 =gl(3,20/3))
ggplot(dat,aes(x=X,y=Y,color=att1,shape=att2)) +
    geom_point(size=5) 

enter image description here

You can do it in the base plot also, but you should generate manually the legend ...

plot(dat$X,dat$Y,pch=as.integer(dat$att1),col=as.integer(dat$att1))

enter image description here

like image 177
agstudy Avatar answered Oct 12 '22 14:10

agstudy


Is this what you want? [df is your data formatted as above.]

library(ggplot2)
ggplot(df) + geom_point(aes(x=X,y=Y,color=factor(att1),shape=att2),size=5)

Produces this with your data:

like image 41
jlhoward Avatar answered Oct 12 '22 14:10

jlhoward