In order to visualize the data represented in the ACLED app, I wanted to include some circle charts to show the proportion of violent events by type and by actor, as seen here:
Here’s the obstacle: for a given set of data over a variable number of days, I did not know precisely how many sections the pie chart would have. The number of actors or types could change. This presents an issue because Chart.js takes in the data as an array of hashes, and each section gets passed in as a hash along with its section color and highlight color. I needed a way to assign these inside of an array that might change in size.
So, I created a method to do this for me:
This method has two paramenters (arguments): the data for the chart and a list of colors to assign to each of the sections. It loops through a list of, in my app, nine colors:
On the left are the colors, and on the right of each color is another color, similar to the color on the left but lighter. This is the color that the Chart uses to highlight a section when a user hovers over it (see the hover action on “Military Forces of Somalia” above).
So how do we do this? We look through the hash and create new hashes for each data section, so we can create a data array that changes in size according to the number of sections represented in the data. If there are more sections than there are color choices, we loop back through the color array. So the colors repeat. For me, this was a sufficient solution. You may prefer to have a bigger list of colors or to auto-generate colors. I worried about getting seven shades of brown with the latter method, hence the list approach.
highlight_color instead of the traditional
Actually, that last one isn’t a terrible idea. Maybe I need to go back and do it that way.