【问题标题】:Using scale_x_date in ggplot2 with different columns在具有不同列的 ggplot2 中使用 scale_x_date
【发布时间】:2017-06-26 14:28:42
【问题描述】:

假设我有以下数据:

Date      Month  Year  Miles Activity
3/1/2014    3     2014  72   Walking
3/1/2014    3     2014  85   Running
3/2/2014    3     2014  42   Running
4/1/2014    4     2014  65   Biking
1/1/2015    1     2015  21   Walking
1/2/2015    1     2015  32   Running

我想制作图表,显示每个月日期的里程总和,按年份分组和着色。我知道我可以用每个活动每月的里程总和制作一个单独的数据框,但问题在于显示。 Excel 中的内容基本上就是我想要的——这些总和按时间顺序显示并按活动着色。

我知道 ggplot2 有一个 scale_x_date 命令,但我在问题的“双方”都遇到了问题——如果我使用 Date 列作为我的 X 变量,它们不会相加。但是,如果我将我的数据按我想要的方式汇总在一个单独的数据框中(即,每个月的每个活动只有一行),我不能同时使用 MonthYear 作为我的 x 轴——至少,我不能以任何方式让scale_x_date 理解。

(而且,我知道,如果 Excel 可以正确绘制图表,为什么不直接使用 Excel ——不幸的是,我的数据太大,以至于 Excel 运行非常缓慢,继续使用它是不可行的。)有什么想法吗?

【问题讨论】:

    标签: r excel date ggplot2 axis-labels


    【解决方案1】:

    下面的小数据集对我来说很好。如果您将 data.frame 转换为 data.table,您只需几个预处理步骤即可将数据汇总到每个活动的英里数和月份级别。我在代码中留下了一些 cmets,让您了解发生了什么,但它应该是不言自明的。

     # Assuming your dataframe looks like this
     df <- data.frame(Date = c('3/1/2014','3/1/2014','4/2/2014','5/1/2014','5/1/2014','6/1/2014','6/1/2014'), Miles = c(72,14,131,534,123,43,56), Activity = c('Walking','Walking','Biking','Running','Running','Running', 'Biking'))
    
     # Load lubridate and data.table
    library(lubridate)
    library(data.table)
    
    # Convert dataframe to a data.table
    setDT(df)
    df[, Date := as.Date(Date, format = '%m/%d/%Y')] # Convert data to a column of Class Date -- check with class(df[, Date]) if you are unsure
    df[, Date := floor_date(Date, unit = 'month')] # Reduce all dates to the first day of the month for summing later on
    
    # Create ggplot object using data.tables functionality to sum the miles 
    ggplot(df[, sum(Miles), by = .(Date, Activity)], aes(x = Date, y = V1, colour = factor(Activity))) + # Data.table creates the column V1 which is the sum of miles
      geom_line() +
      scale_x_date(date_labels = '%b-%y') # %b is used to display the first 3 letters of the month
    

    【讨论】:

      猜你喜欢
      • 2012-05-21
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 2022-01-14
      • 1970-01-01
      相关资源
      最近更新 更多