r - ggplot2 geom_smooth 以变量为因子

标签 r ggplot2 dataframe

我有一个小问题,我自己无法解决这个问题。

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

我如何在 ggplot2 中获得图表,它显示了 的所有值重量 以及 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")

最佳答案

这是你追求的吗?

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")

关于r - ggplot2 geom_smooth 以变量为因子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35450122/

相关文章:

r - 为每个条形图 r 添加一个标签

r - ggplot 中超过六种形状

删除 R 中具有特定标点符号的特定单词

r - R中每小时分割时间序列数据

r - ggplot2:将各个facet_wrap构面另存为单独的图对象

r - 根据另一列中值的最后 2 位数字创建新列

r - R Shiny :删除ggplot2背景以使其透明

python - 按 'Date' 分组,同时计算其他列的平均值

python - Pandas Dataframe 自动类型转换

python - 从 Pandas 中的相关矩阵创建列表