【问题标题】:How to smooth the curve of a density plot in ggplot?如何平滑ggplot中密度图的曲线?
【发布时间】:2021-08-13 16:45:08
【问题描述】:

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

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

这让我明白了:

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

有谁知道我可以如何解决这些问题?他们让情节很难解释,也没有真正反映我的数据中发生的事情。

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。看来您的数据是离散的。密度图适用于连续数据。您可以尝试使用 adjust= 参数更改默认带宽选项。条形图可能更合适。
  • AnonymousCoward,如果其中一个答案解决了您的问题,请accept it;这样做不仅为回答者提供了一些积分,而且还为有类似问题的读者提供了一些关闭。尽管您只能接受一个答案,但您可以选择对您认为有帮助的人进行投票。 (如果仍有问题,您可能需要编辑您的问题并提供更多详细信息。)谢谢!

标签: r ggplot2 density-plot


【解决方案1】:

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

或者,正如 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")

【讨论】:

    【解决方案2】:

    您选择的数据可视化并不理想。您想比较不同问题/组的 1-7 级结果变量。您可能希望将结果变量的频率映射到 geom_linegeom_area 或两者。

    使用来自Kaggle 的调查数据。

    library(tidyverse)
    
    my_data <- read_csv("~/Downloads/archive/test.csv")
    
    plot_data <- my_data %>%
      select(id, `Inflight wifi service`:`Food and drink`) %>%
      pivot_longer(`Inflight wifi service`:`Food and drink`, names_to = "question", values_to = "response") %>%
      count(question, response) %>%
      group_by(question) %>%
      mutate(freq = n / sum(n))
    
    ggplot(plot_data) +
      geom_area(aes(x = response, fill = question, y = freq), alpha = 0.5)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2023-01-12
      • 2015-02-23
      • 2021-05-25
      • 2021-02-07
      相关资源
      最近更新 更多