在ggplot2中使用不同列的scale_x_date

假设我有以下数据:

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 

我想制作一个图表,显示每个月份的date总和,按年份分组和彩色。 我知道我可以用每个活动的每月里程总和来创build一个单独的数据框,但问题在于显示。 这里在Excel中基本上是我想要的 – 按时间顺序显示和按活动着色的总和。 在这里输入图像说明

我知道ggplot2有一个scale_x_date命令,但遇到问题的“双方”的问题 – 如果我使用Date列作为我的Xvariables,他们没有总结。 但是,如果我总结我的数据如何在一个单独的数据框(即,每个月的每个活动只有一行),我不能使用MonthYear作为我的x轴 – 至less,不以任何方式我可以得到scale_x_date理解。

(而且,我知道,如果Excel正确地绘制图表,为什么不使用Excel?不幸的是,我的数据太大了,Excel运行速度很慢,继续使用它是不可行的。)任何想法?

下面的小数据集适合我。 如果您将data.frame转换为data.table,则只需几个预处理步骤就可以将数据总和达到每个活动和每个月的英里数。 我在代码中留下了一些意见,让你知道发生了什么,但它应该是不言自明的。

  # 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