K23
K23

Reputation: 29

geom_density() for a set of values that are all the same

When I try to generate a density plot for a set of values that are all the same, I get the following plot enter image description here

Here is the code I used:

library(data.table)
library(ggplot2)

test <- data.table(x = c(1, 1, 1, 1,1))
ggplot(test, aes(x = x)) +
  geom_density(fill = "blue", alpha = 0.4)

How do I get the graph to show just vertical line at 1?

Upvotes: 0

Views: 936

Answers (1)

hrbrmstr
hrbrmstr

Reputation: 78792

It's just doing what you told it to do. Lookup the adjust parameter of the density function since that's impacting the bw (bandwidth) parameter. Since you know a bit about your data, you can also change the type of kernel to be more appropriate (though it's really not necessary in this example).

ggplot(test, aes(x = x)) +
  geom_density(fill = "blue", alpha = 0.4, kernel="rectangular", adjust=0.0000001)

enter image description here

The "built-in" density function is not exactly super-accurate (try integrating the x/y results and see how often you get exactly 1). You can use the bkde function in KernSmooth to get a more accurate result/plot:

library(KernSmooth)

den <- bkde(test$x, 
          bandwidth=1, 
          range.x=c(0.99999, 1.00001), 
          truncate=TRUE)

ggplot(data.frame(x=den$x, y=den$y), aes(x, y)) +
  geom_line() + 
  xlim(0, 2)

enter image description here

But, I'm more curious as to what you're trying to achieve vs how.

Upvotes: 3

Related Questions