ggplot2中的geom_smooth如何使用变量作为因子

7

我有一个小问题,可恶的是我无法自己解决。

我有一个简单的数据框,想要用ggplot2绘图。当我将变量weight作为因子时,x轴上出现了所有值,如图2所示,但当我将其作为整数时,却不行,如图1所示。然而,我想使用geom_smooth,它似乎只在图1中生效,而在图2weight是因子时不会生效。

如何在ggplot2中获得一个图形,既显示了weight的所有值,又包含geom_smooth函数?

请参考示例文件:

require(ggplot2)

x <- get.url(https://dl.dropboxusercontent.com/u/109495328/example.csv)
app_df <- read.csv(x, header=T, sep = ",", quote = "", stringsAsFactors = FALSE, na.strings = "..")     
colnames(app_df) <- c("Date", "Weight")

date <- as.Date(strptime(app_df$Date, "%d.%m.%Y"))
weight <- app_df$Weight
df <- na.omit(data.frame(date,weight))

# plot 1 (only few values indicated in x axis)
ggplot(df, aes(date,weight)) +
  geom_point() +
  geom_line(aes(group = "1")) +
  geom_smooth(method = "lm")

# plot 2 (no smooth function)
ggplot(df, aes(date,as.factor(weight))) +
  geom_point() +
  geom_line(aes(group = "1")) +
  geom_smooth(method = "lm")

1
问题不明确。在图表1中,您将获得16个数据点和趋势线(geom_smooth)。同样,在图表2中,您将获得16个点,但是这个图表是错误的,因为权重必须用作整数,而不是因子。 - Didzis Elferts
1
因子变量本质上是分类变量。您无法将线性或任何函数拟合到它们上面。至于整数值未全部显示,您可以使用scale_y_continuous来自定义限制和断点。 - Gopala
嗨,Gopala,你会如何在当前示例中使用 scale_y_continous,以便我在 x 轴上获得与图 2 中相同的 16 个数据点? - Til Hund
我在你的问题中看不到任何图表,而且你的链接已经失效了。也许你可以更新一下问题,这样其他社区成员也能从中学习到东西? - Igor F.
1个回答

2

这是您需要的内容吗?

require(ggplot2)

x <- url("https://dl.dropboxusercontent.com/u/109495328/example.csv")
app_df <- read.csv(x, header=T, sep = ",", quote = "", stringsAsFactors = FALSE, na.strings = "..")     
colnames(app_df) <- c("Date", "Weight")

date <- as.Date(strptime(app_df$Date, "%d.%m.%Y"))
weight <- app_df$Weight
df <- na.omit(data.frame(date,weight))

# plot 1 (only few values indicated in x axis)
ggplot(df, aes(date,weight)) +
  geom_point() +
  geom_line(aes(group = "1")) +
  geom_smooth(method = "lm")

# plot 2 (no smooth function)
ggplot(df, aes(date,as.numeric(as.factor(weight)))) +
  geom_point() +
  geom_line(aes(group = "1")) +
  geom_smooth(method = "lm")

Richo64,非常感谢您的回答。不幸的是,它并不是我想要的。我想要将图1和图2结合起来,其中趋势线与x轴上所有16个数据点一起显示,就像图2中那样。 - Til Hund
这个回答是否有帮助?(链接:https://dev59.com/uJPfa4cB1Zd3GeqPItg_#35263049) - Mist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接