【问题标题】:ggplot2 geom_smooth with variable as factorggplot2 geom_smooth 以变量为因子
【发布时间】:2016-05-28 18:27:10
【问题描述】:

我有一个小问题,我自己解决不了。

我有一个简单的数据框,我想用ggplot2 绘制它。当我使用变量 weight 作为一个因素时,我得到了 x 轴上的所有值,s。 plot 2,但当我将它用作整数时,s 不是。 情节 1。但是,我想使用geom_smooth,它似乎只适用于 plot 1,但不适用于 plot 2,其中 weight 是一个因素.

如何在ggplot2 中获得一个图表,它显示了weight 的所有值以及geom_smooth 函数?

考虑this 示例文件:

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 中,您可以获得 16 个数据点和趋势线 (geom_smooth)。同样在图 2 中,您得到 16 分,但该图是错误的,因为必须将权重用作整数而不是因子。
  • 因子变量本质上是分类变量。你不能为它们拟合线性或任何函数。至于未全部显示的整数值,您可以使用scale_y_continuous 自定义限制和中断。
  • 嗨,Gopala,您将如何在本示例中使用 scale_y_continous,以便我在 x 轴上获得与图 2 中相同的 16 个数据点?
  • 我在您的问题中看不到任何情节,并且您的链接已损坏。也许您可以更新问题,以便社区的其他人也可以从中学习?

标签: r ggplot2 dataframe


【解决方案1】:

这就是你所追求的吗?

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 的组合,其中我有趋势线,所有 16 个数据点都显示在 x 轴上,如图 2 所示。
  • this answer 有帮助吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-04
  • 2020-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-01
  • 2014-09-21
相关资源
最近更新 更多