首页 > 解决方案 > 如果其中一个图有两个或更少的值,为什么 geom_smooth 会为图表中的所有图抛出错误?

问题描述

我有三种风格的数据,并希望在图表中将其显示为三个不同的图。我还想在地块上使用 geom_smooth。当其中一种数据的值少于七个时,无法为该图呈现 geom_smooth。这很好,因为它是为其他地块渲染的。(第二个示例)但是,我注意到当其中一种风味具有两个或更少的值时,不会为图表中的任何图呈现 geom_smooth。我想在其他两种口味上使用 geom_smooth,即使一种口味的数据点低于两个。

我发现警告/错误很难解释,因为它们会根据最后一种风味的数据点数量而变化。

具有两个数据点的示例

library(ggplot2)

dat <- data.frame("Year" = c(1:10, 1:10, 4,5),
                  "Val" = c(46,57,36,58,36,57,36,56,46,58,
                          23,28,26,38,26,37,26,26,36,38,
                          3,5),
                  "Flavour" = c(rep("type A",10), rep("type B", 10), rep("type C",2)))

ggplot(dat, aes(x = Year,
                y = Val,
                color = Flavour,
                group = Flavour)) +
  geom_smooth(alpha = 0.5) +
  geom_line() +
  geom_point()

在此处输入图像描述

具有两个以上数据点的示例

library(ggplot2)

dat <- data.frame("Year" = c(1:10, 1:10, 1:3),
                  "Val" = c(46,57,36,58,36,57,36,56,46,58,
                        23,28,26,38,26,37,26,26,36,38,
                        3,5,5),
                  "Flavour" = c(rep("type A",10), rep("type B", 10), rep("type C",3)))

ggplot(dat, aes(x = Year,
                y = Val,
                color = Flavour,
                group = Flavour)) +
  geom_smooth(alpha = 0.5) +
  geom_line() +
  geom_point()

在此处输入图像描述

标签: rggplot2smoothinggeom

解决方案


推荐阅读