0

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?

1
  • 2
    You can set the limits in scale_x_continuous() to make the axis wider than the data range. Commented Apr 18, 2023 at 14:01

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.