When I try to generate a density plot for a set of values that are all the same, I get the following plot
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?
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)
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)
But, I'm more curious as to what you're trying to achieve vs how.