【问题标题】:smoothing line with categorical variable with ggplot?用ggplot用分类变量平滑线?
【发布时间】:2018-07-29 21:03:05
【问题描述】:

我有一个庞大的数据集,这是一个样本。

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 是一个分类变量。如何通过channelggplot2创建平滑线?

【问题讨论】:

  • 您真的想要平滑线或连接在一起的点吗?
  • 希望有一条平滑线。谢谢。

标签: r ggplot2 smoothing


【解决方案1】:

如果您想使用黄土平滑,您将需要更多数据。因为它位于 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")

【讨论】:

  • 我的数据集非常大。当我这样做时,我收到了这条消息。 “错误:美学必须是长度 1 或与数据相同 (438549): x, y, colour”你知道吗?
  • 您是否运行了factor(...) 部分,这可能会弄乱您的数据,看看dat$basket_size_group 或许?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多