Skip to content

Automating Graphs

From time to time I write R code for colleagues whose data analysis skills are stronger than their coding skills. Often this involves graphing or data manipulation code. One afternoon, my colleague called to ask about modifying a previous set of graphing code I had created months earlier. An easy change, I had it updated in no time. As we hung up the phone, he commented, “This is great! Now I’m going to go and run this code 100 times.” When pushed, he told me he wanted the same graph for each column in his data set, 100 columns in total. This was a detail he had failed to mention in our first conversation. I had modified the code according to his request, but it never occurred to me that he would run it manually 100 times.

I asked him to give me 30 minutes investigate automating the process so he could have all 100 graphs without manually swapping in the variables for the line graph. After consulting the collective wisdom of the Internet (i.e., Googling and piecing together several different StackOverflow threads), this is what I came up with:

This code cycled over each column, named the graph based on the column name, and saved it out to the workspace folder.

Screen Shot 2016-01-27 at 6.07.21 PM

This is the graph it produced, based on my colleague’s specifications.

LIST.OF.WORDS.3This experience taught me two technical things:

  1. Iterating over each column in the data set;
  2. Automatically saving the graph file.

More importantly, it was a good reminder that what people request, in this case the modified graph, is not always what they need. If my colleague hadn’t made his wry remark at the end of our conversation, he would have spent the time and effort to run each graph manually. It is what he thought he had to do. Asking a few more questions about what he needed — seeing his whole picture — not only allowed me to better meet his needs, but also taught him what was possible.

Published inR-Code