Showing posts with label ggplot2. Show all posts
Showing posts with label ggplot2. Show all posts

Monday, December 9, 2013

Graphing my MPG vs Temperature

Updated: 7/9/2014

I use Fuelly to track the fuel mileage in my Toyota Tundra pickup truck. They have a mobile app, so while I'm waiting for the truck to fill up, I log the odometer, and the number of gallons that I put in and then also the price per gallon of fuel and an estimate of my city driving percentage.

Any how, I've noticed a substantial drop in fuel economy when the weather turns cold. So, remembering that I've decided to record the temperature at O'hare every day, I figured I'd try to take a look at the data. Now, I live 40 miles or so north of O'hare, so it's not perfect, but it was a good estimate.

To merge the daily temperature data with the sporadic fillup data, I chose to take the average high temperature for the days between the fillup[i] and fillup[i-1] to use as temperature[i]. I hope that makes sense. Basically, I take the average temperature over the tank of gas.

Let's see what a simple graph of average temperature by MPG looks like…

ggplot(fuel, aes(x=avg.temp, y=mpg)) + geom_point() + 
  geom_smooth(method = lm, se=FALSE) + xlab("AVG Temp") + 
  ylab("MPG") + theme_bw()

plot of chunk unnamed-chunk-3

There's a fairly obvious pattern here. As temperature goes up, my MPG goes up, just as I suspected was happening.

Now, I know this next graph goes against normal data visualization guidelines, but I just think it makes the relationship easier to understand for a lay person. Here, I've plotted both temperate and MPG on the same graph, with MPG in black with it's axis on the left and temperature in red with it's axis on the right.

grid.newpage()

# two plots
p1 <- ggplot(fuel, aes(x=date, y=mpg)) + geom_line() + 
  theme_bw() + xlab("Date") + ylab("MPG (Black)")
p2 <- ggplot(fuel, aes(x=date, y=avg.temp)) + 
  xlab("Date") + ylab("AVG Temp (Red)") +
  geom_line(colour="red") + theme_bw() + 
  theme(axis.title.y=element_text(angle = -90)) %+replace% 
  theme(panel.background = element_rect(fill = NA))

# extract gtable
g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))

# overlap the panel of 2nd plot on that of 1st plot
pp <- c(subset(g1$layout, name == "panel", se = t:r))
g <- gtable_add_grob(g1, 
                     g2$grobs[[which(g2$layout$name == "panel")]], 
                     pp$t, pp$l, pp$b, pp$l)

# axis tweaks
alab <- g2$grobs[[which(g2$layout$name=="ylab")]]
ia <- which(g2$layout$name == "axis-l")
ga <- g2$grobs[[ia]]
ax <- ga$children[[2]]
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + 
  unit(0.15, "cm")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], 
                     length(g$widths) - 1 )
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], 
                     length(g$widths) - 1 )
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 2, pp$b)
g <- gtable_add_grob(g, alab, pp$t, length(g$widths) - 1, pp$b)

grid.draw(g)

plot of chunk unnamed-chunk-4

Credit to this guy, for his dual axis ggplot2 code.

R code available on github here. Follow me on twitter… https://twitter.com/corynissen

Monday, November 25, 2013

Mapping Foodborne Chicago Reports

I help out with a project called Foodborne Chicago, where we search twitter for people in Chicago mentioning "food poisoning" and @reply to them with a link where they can file a report with the city of Chicago's Department of Public Health. The application has been live since March 2013. Since then, we have passed on about 125 reports to the city. For the majority of these reports, an inspection work order is generated and an inspection occurs within about a week of the incident submission.

So... I decided to take a look and see where these submissions were by plotting them on a map. To start, I had a file from our app with three columns, id which is a unique identifier of the submission, restaurant.address which is the address for the submission, and created.at which represents the date that the complaint was submitted. The first step to plotting these submissions on a map was to get the latitude and longitude for the restaurant addresses. I used the ggmap package for this. Originally, I had a custom function that used the free Google geocoding API and parsed the results, then I found the ggmap package and changed over. The results are the same, but it makes the code cleaner and easier to maintain.


Then, I Since I've used the OpenStreetMap package in R in another project, I started with that to make a map. The only gotcha here was that the OpenStreetMap package needs the points in mercator, so there's a conversion step.



The ggmap package makes doing this sorta thing, in conjunction with ggplot2, very simple. Here's the same map as above, using ggmap and Google maps.



Now, since I'm from the area and am not even sure where Chicago's borders are on that map, I downloaded the shapefiles for Chicago from the city of Chicago and added that as an overlay on the map. All I did here was take the last plot (p2) and add the geom_polygon with a low alpha to the map.


This gives a pretty good representation of where our Foodborne Chicago submissions are coming from. Nearly all of them are on the northern half of the city, with a few from beyond the city limits altogether. It's pretty remarkable how easy the ggmap and ggplot2 folks have made creating maps like this. Thanks guys...

The whole project, including making an animated gif and doing some cloudmade maps is on github here... https://github.com/corynissen/foodborne_chicago_report_map

Check out Foodborne Chicago on twitter... https://twitter.com/foodbornechi

And myself on twitter... https://twitter.com/corynissen

Wednesday, April 17, 2013

ggplot dodged vs faceted bar chart

Updated: 7/9/2014

I've been bowling once per year at a charity event for the last few years and have kept track of the outcomes to share my group. I used ggplot2 to create a bar chart for the scores. Below are two graphs, one is dodged, the other is faceted. There's no right way here, but you can see the code and decide for yourself which is more aesthetically pleasing.

First is the dodged one…

library(ggplot2)
df <- read.csv("bowling.csv", strip.white=T)
a <- 1:200

ggplot(df, aes(x=factor(name), y=score)) +
  geom_bar(position="dodge", stat="identity",aes(fill=factor(game))) +
  coord_cartesian(ylim=c(50, 150)) + scale_y_continuous(breaks=a[a%%10==0]) +
  xlab("") + ylab("Score") + scale_fill_discrete(name="Game") +
  theme(axis.text.x = element_text(size=14))

plot of chunk unnamed-chunk-2

And next is the faceted one…

ggplot(df, aes(x=factor(game), y=score)) +
  geom_bar(stat="identity",aes(fill=factor(game))) + facet_grid(.~name) +
  coord_cartesian(ylim=c(50, 150)) + scale_y_continuous(breaks=a[a%%10==0]) +
  scale_fill_discrete(name="Game") + xlab("") + ylab("Score")

plot of chunk fig.align:center

The color is redundant in the faceted one, since there are labels for the game number. I kept the color in to make comparison with the dodged one easier.

Here's the code to produce these two graphs. The full code with the data to produce these plots and also the blog post using Rmarkdown is available in my github repo.

@corynissen on twitter