Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stacked Area Histogram in R

Tags:

r

ggplot2

charts

I ran a Pig job on a Hadoop cluster that crunched a bunch of data down into something R can handle to do a cohort analysis. I have the following script, and as of the second to last line I have the data in the format:

> names(data)
[1] "VisitWeek" "ThingAge"    "MyMetric"

VisitWeek is a Date. ThingAge and MyMetric are integers.

The data looks like:

2010-02-07     49  12345

The script I have so far is:

# Load ggplot2 for charting 
library(ggplot2);

# Our file has headers - column names
data = read.table('weekly_cohorts.tsv',header=TRUE,sep="\t");

# Print the names
names(data)

# Convert to dates
data$VisitWeek = as.Date(data$VisitWeek)
data$ThingCreation = as.Date(data$ThingCreation)

# Fill in the age column
data$ThingAge = as.integer(data$VisitWeek - data$ThingCreation)

# Filter data to thing ages lt 10 weeks (70 days) + a sanity check for gt 0, and drop the creation week column
data = subset(data, data$ThingAge <= 70, c("VisitWeek","ThingAge","MyMetric"))
data = subset(data, data$ThingAge >= 0)

print(ggplot(data, aes(x=VisitWeek, y=MyMetric, fill=ThingAge)) + geom_area())

This last line does not work. I've tried lots of variations, bars, histograms, but as usual R docs defeat me.

I want it to show a standard Excel style stacked area chart - one time series for each ThingAge stacked across the weeks in the x axis, with the date on the y axis. An example of this kind of chart is here: http://upload.wikimedia.org/wikipedia/commons/a/a1/Mk_Zuwanderer.png

I've read the docs here: http://had.co.nz/ggplot2/geom_area.html and http://had.co.nz/ggplot2/geom_histogram.html and this blog http://chartsgraphs.wordpress.com/2008/10/05/r-lattice-plot-beats-excel-stacked-area-trend-chart/ but I can't quite make it work for me.

How can I achieve this?

like image 770
rjurney Avatar asked Dec 23 '22 05:12

rjurney


1 Answers

library(ggplot2)
set.seed(134)
df <- data.frame(
    VisitWeek = rep(as.Date(seq(Sys.time(),length.out=5, by="1 day")),3),
    ThingAge = rep(1:3, each=5),
    MyMetric = sample(100, 15))

ggplot(df, aes(x=VisitWeek, y=MyMetric)) + 
    geom_area(aes(fill=factor(ThingAge)))

gives me the image below. I suspect your problem lies in correctly specifying the fill mapping for the area plot: fill=factor(ThingAge)

enter image description here

like image 189
learnr Avatar answered Dec 27 '22 06:12

learnr