Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a plot with customized points in R?

Tags:

plot

r

graphics

I know I can create a plot with line and dots using the type = "o" argument in the plot command. I would like some more control over this -- I want to be able to draw the "o" as full dots, with black border and fill-in color of my choice, of customized size and of a different color than the line. Same for the line, I want to make it thicker, and of my choice of color. How would I go on about doing that?

What I found until now is just a plain

 plot(y, type= "o")

which is too poor for my needs.

I am not interested in using ggplot, but instead use the internal plot library of R. Any help appreciated.

like image 738
kloop Avatar asked Nov 28 '22 09:11

kloop


2 Answers

All the information you need should be present in ?plot and ?points, as suggested by @BenBolker. In particular, you want to be using pch=21, and specifying background colour with the bg argument, size with cex, and line width with lwd.

If you want the line to be a different thickness to the point borders, you need to plot the line first, and then overlay the points.

For example:

y <- sample(10)
plot(y, lwd=6, type='l')
points(y, bg='tomato2', pch=21, cex=3, lwd=3) # tomato2 is a personal fave

enter image description here

You could also provide a vector of lwd, cex and col to the points call:

plot(y, lwd=6, type='l')
points(y, bg=rainbow(10), pch=21, cex=seq(1, by=0.2, length.out=10), 
       lwd=seq(2, by=1, length.out=10))

enter image description here

like image 90
jbaums Avatar answered Dec 04 '22 13:12

jbaums


You could use layering (I don't work in base too much any more as a social researcher I love the facet_grid of ggplot, so there may be a better way) as in:

x <- sort(rnorm(25))
y <- sort(rnorm(25))
z <- as.factor(sample(LETTERS[1:5], 25, r=TRUE))

plot(x, y, pch = 19, cex = 1.3)
par(new = TRUE)
plot(x, y, pch = 19, cex = 1, col = z)

Which gives you: enter image description here

like image 20
Tyler Rinker Avatar answered Dec 04 '22 13:12

Tyler Rinker