Plotting densities in R

浪子不回头ぞ 提交于 2019-12-24 03:03:30

问题


So, I am plotting densities (histograms). For example:

d <- density(table[table$position==2,]$rt)

But, I want to plot multiple densities on the same plot. For instance, I also want to plot

density(table[table$position==3,]$rt)
density(table[table$position==4,]$rt)
density(table[table$position==5,]$rt)

Furthermore, I want to specify the center point for each of these densities.

Another way to ask this question is, how can I manually shift a density plot over by a certain number of x units? (for instance, increase all x values by 5)


回答1:


As with many R analysis functions, saving the output is your friend. So is ?density.

foo<-density(something)

names(foo)

"x", "y" , "bw", "n" , "call" ,"data.name"

So, plot(foo$x+5, foo$y, t='l') And you're done so far as I can tell.




回答2:


For the piece of your question about plotting multiple densities on the same plot, use lines:

dat <- data.frame(x = rnorm(100), y = rnorm(100) + 2, z = rnorm(100) + 5)

plot(c(-2.5,8),c(0,0.5),type = "n")
lines(density(dat$x))
lines(density(dat$y))
lines(density(dat$z))

You open an empty plotting device using plot(...,type = "n") and then draw on it using lines or points, etc.



来源:https://stackoverflow.com/questions/7604838/plotting-densities-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!