Easily creating charts in Jekyll
I want to be able to create charts in my blog posts without pre-rendering images in another application. It turns out this is possible with Chart.js and a little bit of middleware. Here are some examples, with an explanation and source available below:
Example 1: Racial Demographics of U.S. Cities
This table shows a demographic profile of select U.S. cities in 2010.
Example 2: Walmart Store Counts
This table shows the growth in the number of domestic and international Walmarts. Source
|Sam's Club segment||579||591||611||605||609||611||620|
How it works
<div data-figure="chart" data-focus="chart"></div> | City | Whites | Blacks | Hispanics | Asians | Other | | ------------- | ------:| ------:| ---------:| ------:| -----:| | New York | 33.3% | 23.0% | 28.6% | 12.7% | 2.4% | | Chicago | 31.7% | 19.6% | 28.9% | 5.5% | 14.3% | | San Francisco | 41.9% | 6.1% | 15.1% | 33.3% | 3.6% | | Seattle | 66.3% | 7.9% | 6.6% | 13.8% | 5.4% |
There are a few configuration options, which can be set using attributes on the div. The supported attributes are:
||chart||Required to indicate that this div and the following table should be rendered with a chart.|
||line or bar||Type of chart to render.|
||table or chart||Which tab should be initially focused.|
||columns or rows||Is each row a new series in the data, or is each column?|
||Any other data attributes are passed to Chart.js directly. For example, the Walmart chart above uses
Doing it yourself
I've uploaded the two JS files that I used to a gist. Note that the Chart.js I'm using is a modified version of this pull request. The pull request is needed to support legends, and my additions add basic support for variable font sizes in the legend.
The code could use some work. Notably, it doesn't support anything other than bar and line charts. It would be nice to get pie charts supported. Let me know if you add support for them or make any other changes; I'd love to hear about your ideas.