首页 > 解决方案 > 如何平滑ggplot中密度图的曲线?

问题描述

我正在尝试覆盖以整数比例 (1-7) 表示的结果变量的密度图。现在我正在使用:

ggplot(dface, aes(Current.Mood, fill = NewCode))+ geom_density(alpha = 0.1)

这让我:

在此处输入图像描述

出于某种我不明白的原因,ggplot 将山谷置于整数值之间(如下图所示)有谁知道我怎样才能让情节平滑这些?

有谁知道我怎样才能解决这些问题?他们使情节很难解释,并且没有真正反映我的数据中发生的事情。

标签: rggplot2density-plot

解决方案


geom_density(bw=..)在这里很有用。

      bw: The smoothing bandwidth to be used. If numeric, the standard
          deviation of the smoothing kernel. If character, a rule to
          choose the bandwidth, as listed in 'stats::bw.nrd()'.
ggplot(mtcars, aes(cyl)) + geom_density(bw = 0.1) + labs(title = "bw = 0.1")
ggplot(mtcars, aes(cyl)) + geom_density() + labs(title = "bw default")
ggplot(mtcars, aes(cyl)) + geom_density(bw = 2) + labs(title = "bw = 2")

0.1的带宽

默认带宽

带宽 2

或者,正如 MrFlick 建议的那样,您可以使用adjust=

  adjust: A multiplicate bandwidth adjustment. This makes it possible
          to adjust the bandwidth while still using the a bandwidth
          estimator. For example, 'adjust = 1/2' means use half of the
          default bandwidth.
ggplot(mtcars, aes(cyl)) + geom_density(adjust = 0.5) + labs(title = "adjust = 0.5")
ggplot(mtcars, aes(cyl)) + geom_density(adjust = 0.9) + labs(title = "adjust = 0.9")

调整 0.5

调整 0.9


推荐阅读