Last updated on 2019-10-30
Previous Lesson: Learning C3.js – Lesson 4 – Bar Charts.
As I wrote before, we (humans) have the capacity to get information from visual data very fast. When we are using one chart type we can show a lot of information in a chart, and when we have two chart types, we can show even more information (when used wisely). We can have more than one type of data shown in the same chart. Let’s see how this works in C3.js
.
For this example, I’m going to visualize the sales of how the number of widgets sold in each city relates to the world GDP. Please note that all numbers here are imaginary :-):
var chart = c3.generate({ bindto: '#chart', data: { x: 'x', columns: [ ['x', 2015, 2016, 2017, 2018, 2019], ['London, UK', 340, 560, 320, 750, 350], ['Paris, France', 450, 360, 260, 730, 340], ['Milan, Italy', 740, 340, 60, 230, 530], ['GDP', 34, 53, 63, 24, 65] ], type: 'bar', types: { GDP: 'line' }, axes: { GDP: 'y2' } }, axis: { x: { type: 'category', }, y: { label: 'Sales' }, y2: { show: true, label: 'GDP' } }, legend: { hide: 'GDP' } });
First, in the data
property, I define a series for the x
axis which is names x
, and give values to the axis series and to the other series that I’m visualizing. After this, I define the default type for the chart (which is bar
) and that the GDP
series is not a bar
but a line
. Finally, I define that the GDP
series has a different axis. Second, in the axis
property, the x
series is defined as a category
which makes the bar show between axis ticks and not on the ticks, and I set a label for both y
axes. The first y
axis is shown by default so the show
property only needs to be defined for the second axis. Lastly, I define that the label for the GDP
should not be shown, as it is not needed because it’s already shown in the y2
axis. Note here that I leave it to the viewer to interpret that the bars refer to the sales and the lines refer to the GDP, but since cities don’t have GDP I think it’s best to do it this way (but you can leave the legend for GDP by removing the legend
property at the end of the code).
This is the result:
Taking a look at the chart there seems to be some negative correlation between sales and GDP, especially in Paris but the inverse happens in Milan. Something worth investigating :-).
That’s all for today’s lesson. The code for this lesson and all other lessons is in my GitHub repo. Hope you’ve enjoyed this lesson, and until next time, happy coding!
Be First to Comment