繁体   English   中英

用ggplot平滑线与分类变量?

[英]smoothing line with categorical variable with ggplot?

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

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 ,我想用数据绘制平滑线。 x轴是basket_size_group ,y轴是pct_tripschannel是在一个组ggplot2 问题在于basket_size_group是一个分类变量。 如何使用ggplot2channel创建平滑线?

如果要使用光滑的黄土,则需要更多数据。 坐到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")

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM