Rick Arko
Rick Arko

Reputation: 680

Creating a HeatMap in R with 2 Variables

I'm trying to create a HeatMap in R in order to visualize the following data.

State    Discount
LA      0.118749612
MO      0.127916129
IA      0.129584375
NE      0.138754902
GA      0.146281061

I don't have a lot of experience beyond simply using the built in heatmap() function. However because the state variable is a factor this doesn't work. My next thought was to try and use ggplot2

ggplot(data = dat, aes(State))+ geom_tile( fill = dat$Discount)

However I keep getting this error which I don't fully understand.

Error in eval(expr, envir, enclos) : object 'y' not found
In addition: Warning messages:
1: In min(x, na.rm = na.rm) :
  no non-missing arguments to min; returning Inf
2: In max(x, na.rm = na.rm) :
  no non-missing arguments to max; returning -Inf
3: In min(diff(sort(x))) : no non-missing arguments to min; returning Inf 

I'm not necessarily sure that a heatmap is the best way to visualize my data it was just my first thought. I'm also looking into using the mapdata package to plot a US map showing these differences in discount level by color but haven't come up with a good way of doing so yet. Any help I can get would be greatly appreciated, thanks.

Upvotes: 1

Views: 2134

Answers (1)

Rick Arko
Rick Arko

Reputation: 680

I wound up visualizing my data as follows:

First I added a column to my original data so that I could merge it with state data available in R. So my data file (called GregUSHeatMap) would now look something like this:

State          Code   Discount
vermont         VT    0.02
maine           ME    0.025
massachusetts   MA    0.042073333
south dakota    SD    0.074503704

Then I ran the following:

require(mapdata)
states <- map_data("state")
merge <- merge(states, GregUSheatmap, by = "region")
merge <- arrange(merge, order)
heatmap1 <- qplot(long, lat, data = merge, group = group, fill = Discount, geom = "polygon")

Producing the following: enter image description here

Upvotes: 2

Related Questions