There is some value to storing a plot in variable first

24. December 2016 programming, r 0
There is some value to storing a plot in variable first

Today I learned the value of assigning a ggplot chart to a variable and then plotting. Previously, I would write the code for all elements in the chart and plot it right away. I have been frustrated with a particular heat map as of late because the legend title directly references the variable in my data frame and I couldn’t figure out how to change it. I needed to call out that the legend values were actually in thousands and update the title, but I wasn’t having any luck until today.

After a few searches, I came across a stack overflow article that described one approach to solving this problem. That was when I realized how much value I was missing out on by plotting right away. Most of the manipulations can be performed from within the functions for ggplot, but I think this makes it a bit easier.

Create a heat map using ggplot and assign it to value ‘p’

p = heatmap_data %>% ggplot(aes(hour, wday)) + theme_minimal() + geom_tile((aes(fill = uniques)), color = "white") + scale_fill_gradient(low = "navyblue", high = "gold") + labs(title = "Unique Visitors 10/5/16 - 12/22/16", x = "Hour of Day", y = "Weekday")

If you want to see everything that makes the plot tick, use str(p).

The value I was looking for was in p$labels$fill. To update the legend title from “uniques” to “Uniques (1000)” all I had to do is use type the following line:

p$labels$fill = "Uniques (1000)"

 

Update: 

It really helps to re-read the documentation for ggplot package–it’s just sooooo long.  Shortly after writing this, I found that ggplot already has this functionality built-in to the labs() function.  The following line sets the legend title by updating the fill parameter.

p = p + labs(fill = "Uniques (1000)")

What I actually ended up doing was integrating the fill parameter into my preexisting labs call in my heat map.

p = heatmap_data %>% ggplot(aes(hour, wday)) + theme_minimal() + geom_tile((aes(fill = uniques)), color = "white") + scale_fill_gradient(low = "navyblue", high = "gold") + labs(title = "Unique Visitors 10/5/16 - 12/22/16", x = "Hour of Day", y = "Weekday", fill = "Uniques (1000)")


Leave a Reply