Monday, July 6, 2015

Turn-Key Polar Coordinates

In the search for new, interesting, or clear ways to visualize your data, consider the value of plotting things on a circle. Instead of a bar chart, a pie chart. Or instead of a line graph, a radar plot. The R package ggplot2 makes this easy as "pi" (forgive the pun) with the "coord_polar()" modifier. All the R code (it's not much) to reproduce these examples can be found at our bitbucket repository.

Observe a normal bar chart:

Treat the x-axis as a set of polar coordinates, and you now have a pie chart:


Similarly, observe a normal scatter plot:


Deftly re-plot while treating the x-axis as polar coordinates:



Check out the code, and you'll notice that the only extra step is to add the line specifying which axis should be treated as polar coordinates:

 
 # Polar Coordinates  
   
 library(ggplot2)  
   
 s = c("A","E","I","O","U")  
 random_data = data.frame(x = factor(sample(s, 50, replace=T)))  
   
 p = ggplot(random_data, aes(x=x)) +   
   geom_bar(width = 1, colour = "black")  
 print(p)  
   
 ggsave('normal_bar_chart.jpg')  
   
 p2 = ggplot(random_data, aes(x=x)) +   
  geom_bar(width = 1, colour = "black") +  
  coord_polar()  
 print(p2)  
   
 ggsave('polar_coordinates_bar_chart.jpg')  
   
   
 random_data2 = data.frame(x = runif(50, 0, 5), y = runif(50, 0, 10))  
   
 p = ggplot(random_data2, aes(x=x,y=y)) +   
   geom_point(size = 4, alpha=0.5)  
 print(p)  
   
 ggsave('scatter_plot.jpg')  
   
 p = ggplot(random_data2, aes(x=x,y=y)) +   
   geom_point(size = 4, alpha=0.5) +   
   coord_polar(theta="x")  
 print(p)  
   
 ggsave('polar_coordinates_scatter_plot.jpg')  
   

No comments:

Post a Comment