首页 文章

ggplot2 geom_smooth,变量为因子

提问于
浏览
2

我有一个小问题,我可以荒谬地解决自己 .

我有一个简单的数据框,我想用 ggplot2 绘图 . 当我使用变量 weight 作为因子时,我得到x轴中的所有值,s . 情节2,但不是当我用它作为整数时,s . 但是,我想使用 geom_smooth ,这似乎仅适用于情节1,但不适用于情节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 回答

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

相关问题