r - 使用 ggplot 用分类变量平滑线?

标签 r ggplot2 smoothing

我有一个巨大的数据集,这是一个示例。

data.frame(basket_size_group = c("[0,2]", "[0,2]", "(2,4]", "(2,4]", "(4,6]"),
       channel = c("offline", "online/mobile", "offline", "online/mobile", "offline"), 
       pct_trips = c(0.004, 0.038, 0.0028, 0.0082, 0.0037))

通过使用ggplot2,我想用数据绘制平滑线。 Xaxis 是 basket_size_group,yaxis 是 pct_tripschannelggplot2 中的一个组。问题在于 basket_size_group 是一个分类变量。如何使用ggplot2 channel 创建平滑线?

最佳答案

如果您想使用黄土平滑,您将需要更多数据。因为它位于 stat_smooth() 将失败并出现错误:

Computation failed in `stat_smooth()`:
NA/NaN/Inf in foreign function call (arg 5)

除非您指定method = "lm"

您还必须明确使用 stat_smooth() 层并定义 group = channel。您也可以在顶层执行此操作,但如果没有它,stat_smooth 将尝试使用 xcolor 进行组汇总。

# factor it to plot in order
dat$basket_size_group <- factor(dat$basket_size_group, levels = c("[0,2]", "(2,4]", "(4,6]"))

ggplot(dat, aes(basket_size_group, pct_trips, color = channel)) +
    geom_point() +
    stat_smooth(aes(group = channel), method = "lm")

enter image description here

关于r - 使用 ggplot 用分类变量平滑线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48869368/

相关文章:

javascript - 在 highcharter 中包含导出 csv

r - `venneuler` 中的维恩图 `R` : delete the name of the set from the plot and add elements name

r - 一起使用facet_grid和facet_wrap

opencv - 应用平滑过滤器(双边、高斯、vs.)和色彩空间

java - 如何优化动画?

R:layout() 影响绘图区域的边距大小

r - R 中的条形图 - 恢复 xlim 并使用 par(new=T)

r - 从 ggplot 中提取数据

r - 如何创建要插入到 ggplot 中的对象(当有多个带 + 的部分时)?

r - r错误: Complex matrix?