ggplot2密度图与离散数据

问题描述 投票:-1回答:1

我想用以下数据创建密度图:

 interval       fr      mi      ab
0x              9765    3631    12985
1x              2125    2656    601
2x              1299    2493    191
3x              493     2234    78
4x              141     1559    20
5x and more     75      1325    23

在X轴上我希望有间隔,在Y轴上,我想要有不同颜色的“fr”,“mi”和“ab”的密度。

我的想象力就像这张图。

enter image description here

我的问题是我不知道如何在Y轴上获得密度。我用geom_density试了一下,但是没用。我完成的最好结果是使用以下代码:

DS29 <-as.data.frame(DS29)
  DS29$interval <- factor(DS29$interval, levels = DS29$interval)
  DS29 <- melt (DS29,id=c("interval"))
output$DS51<- renderPlot({
  plot_tab6 <- ggplot(DS29, aes(x= interval,y = value, fill=variable, group = variable)) +
    geom_col()+
    geom_line()
  return(plot_tab6)
})

这给了我以下情节,这不是我想要的结果。你知道我怎么能得到我想要的结果吗?非常感谢你。

enter image description here

r plot ggplot2 density-plot
1个回答
0
投票

看到您的示例数据,我不确定您是否要使用geom_density。如果键入?geom_density,您将看到一些示例代码。如果我从帮助页面中提取一个示例,您可能会看到缺少的内容。

ggplot(diamonds, aes(depth, fill = cut, colour = cut)) +
geom_density(alpha = 0.1) +
xlim(55, 70)

对于x轴,depth是连续变量,而不是分类变量。您当前的数据在x轴上有一个分类变量。对于geom_density,您正在寻找x轴上某个值的密度。上面的示例代码表明,分类为“理想”的钻石密度在61.5-62附近具有高密度,这表明最大比例的“理想”钻石的深度值约为61.5-62。实际上,“理想”钻石深度的平均值是61.71。这意味着您需要多个数据点来计算密度。您的数据每个组的每个间隔只有一个数据点(例如,ab,fr,mi)。因此,我认为您的数据还没有为计算密度做好准备。

如果你想使用当前数据绘制类似于你在问题中建议的图形,我认为你需要1)将interval转换为数字变量,2)将数据转换为长格式,3)使用stat_smooth

library(tidyverse)

mydf %>%
mutate(interval = as.numeric(sub(x = as.character(interval), pattern = "x", replacement = ""))) %>%
gather(key = group, value = value, - interval) -> temp

ggplot(temp, aes(x = interval, y = value, fill = group)) +
stat_smooth(geom = "area", span = 0.4, method = "loess", alpha = 0.4)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.