Search code examples
rggplot2graphdensity-plot

How to extend a density ggplot so that it trails off to zero


I feel like this should be easy but It's been hours of searching and I can't find anything.

I have a density curve below made with the following code

ggplot()+
       geom_density(data = onlyOne, aes(x = log10(frequency), weight = count), bw = 0.2, fill="black", alpha = 0.5)+
       geom_density(data = tableOfGraphData, aes(x = log10(frequency.x), weight = count.x), bw = 0.2, fill = "red", alpha = 0.5)+
       coord_cartesian(xlim = c(-4, 0))+
       theme_light()

enter image description here

I need the figures to have that specific x-axis range but it's driving me nuts that the curves just cut off where their data ends. How do I get the curves to continue to the edge of the figure so that they simply trail off to zero? Theoretically, this would be like having just a bunch of zeros in the data going off to infinity on both sides no?

Does anybody know how to do this?


Solution

  • We don't have your data, but let's create a similar data set to your own with the same names and approximate structure:

    set.seed(12)
    
    onlyOne <- data.frame(frequency = 10^rnorm(50, -4), count = 1)
    tableOfGraphData <- data.frame(frequency.x = 10^rnorm(50), count.x = 1)
    
    onlyOne <- onlyOne[onlyOne$frequency > 0.0001,]
    tableOfGraphData <- tableOfGraphData[which(tableOfGraphData$frequency.x < 1),]
    

    Now we can see that with your plotting code, we get the same issue:

    ggplot() +
      geom_density(data = onlyOne, aes(x = log10(frequency), weight = count), 
                   bw = 0.2, fill="black", alpha = 0.5) +
      geom_density(data = tableOfGraphData, 
                   aes(x = log10(frequency.x), weight = count.x),
                   bw = 0.2, fill = "red", alpha = 0.5) +
      coord_cartesian(xlim = c(-4, 0)) +
      theme_light() 
    

    enter image description here

    To resolve the issue, simply replace coord_cartesian with xlim, using limits that include the point where the density trace meets the x axis:

    ggplot() +
      geom_density(data = onlyOne, aes(x = log10(frequency), weight = count), 
                   bw = 0.2, fill="black", alpha = 0.5) +
      geom_density(data = tableOfGraphData, 
                   aes(x = log10(frequency.x), weight = count.x),
                   bw = 0.2, fill = "red", alpha = 0.5) +
      xlim(-4.6, 0.6) +
      theme_light() 
    

    enter image description here