1
votes

I would like to create a density plot with ggplots2 from a matrix with a variable column and a count column.

a<-as.data.frame(matrix( c(1:10,sample(c(200:300),size=10)), ncol=2,nrow=10))

For a histogram I would simply use stat=identity

ggplot(a,aes(x=V1,y=V2))+geom_bar(stat="identity")

What I would like is to be able to use V2 values as counts to calculate the density across V1. I could normalize my data and smoothen over that, but was wondering if there is anyway to use geom_density or stat_density or something similar directly. Thnx!

2

2 Answers

2
votes

First rescale your data

a$V2<-a$V2/sum(a$V2)

Then you just need tell ggplot2 that the second column is the weight of your data in the density computation

ggplot(a,aes(x=V1,weight=V2)) + geom_density(size=1) 
0
votes
  density(a[,1])
  density(a[,2])
  plot(density(a[,1]))
  plot(density(a[,2]))

Hope this helps.