1

Possible Duplicate:
Shading a kernel density plot between two points

I want to produce a density plot with certain portion highlighted..

myd <- c(2,4,5, 4,3,2,2,3,3,3,2,3,3,4,2,4,3,3,3,2,2.5, 2, 3,3, 2.3, 3, 3, 2, 3)

I want to create density plot and color, the portion greater than 3 to end of the curve .

My unsuccessful codes

plot(density(myd),xlim=c(0,5))

polygon(c(3, myd, max(myd)),c(0,density(myd),0.6),col="tan")
polygon(c(3, myd, max(myd)),c(0,density(myd),0.6),col="tan")
Error in xy.coords(x, y) : 'x' and 'y' lengths differ

polygon(c(3, myd, max(myd)),c(0,myd,0.6),col="tan")

produce a graph, obviously but awful, not closer to what I need !

Community
  • 1
  • 1
jon
  • 11,186
  • 19
  • 80
  • 132

1 Answers1

1

You need to use the values from your density, not your original data.

dens <- density(myd)
polygon(c(3, dens$x[dens$x>3 & dens$x < 5], 5), c(0, dens$y[dens$x>=3 & dens$x <= 5], 0),col="tan")

That's close but since the default plot parameters go out beyond 5 you should select values maybe out to 6. The default plot behaviour will be to just clip. You also might be best off plotting without a box, or x-axis and then placing the x-axis at 0. That way you'll get something more like what you might expect. Try this...

dens <- density(myd)
plot(dens, xlim = c(0, 5), xaxt = 'n', bty = 'n')
axis(1, pos = 0)
polygon(c(3, dens$x[dens$x>3 & dens$x < 6], 6), c(0, dens$y[dens$x>=3 & dens$x <= 6], 0),col="tan")
John
  • 23,360
  • 7
  • 57
  • 83