使用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
,我想用数据绘制平滑线。 Xaxis 是 basket_size_group
,yaxis 是 pct_trips
,channel
是 ggplot2
中的一组。问题是 basket_size_group
是一个分类变量。如何通过 channel
和 ggplot2
?
创建平滑线
如果你想使用黄土光滑,你需要更多的数据。因为它位于 stat_smooth()
将失败并出现错误:
Computation failed in `stat_smooth()`:
NA/NaN/Inf in foreign function call (arg 5)
除非您指定 method = "lm"
。
您还必须明确 stat_smooth()
层并定义 group = channel
。您也可以在顶层执行此操作,但如果没有它,stat_smooth
将尝试使用 x
和 color
进行分组汇总。
# 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")
我有一个庞大的数据集,这是一个示例。
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_trips
,channel
是 ggplot2
中的一组。问题是 basket_size_group
是一个分类变量。如何通过 channel
和 ggplot2
?
如果你想使用黄土光滑,你需要更多的数据。因为它位于 stat_smooth()
将失败并出现错误:
Computation failed in `stat_smooth()`:
NA/NaN/Inf in foreign function call (arg 5)
除非您指定 method = "lm"
。
您还必须明确 stat_smooth()
层并定义 group = channel
。您也可以在顶层执行此操作,但如果没有它,stat_smooth
将尝试使用 x
和 color
进行分组汇总。
# 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")