R语言 如何扩展密度ggplot,使其逐渐接近零

mgdq6dx1  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(102)

我觉得这应该很容易,但它已经搜索了几个小时,我找不到任何东西。
我用下面的代码做了一个密度曲线

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()

我需要的数字有特定的x轴范围,但它的驱动器我坚果,曲线只是切断他们的数据结束的地方。我如何得到的曲线继续到边缘的数字,使他们只是尾随到零?理论上,这将是像只有一堆零的数据,在双方都走向无穷大不是吗?
有人知道怎么做吗?

zyfwsgd6

zyfwsgd61#

我们没有您的数据,但让我们创建一个与您自己的数据集相似的数据集,具有相同的名称和近似结构:

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),]

现在我们可以看到,使用您的绘图代码,我们得到了相同的问题:

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()

要解决这个问题,只需将coord_cartesian替换为xlim,使用包括密度迹线与x轴相交的点的限制:

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()

相关问题