ThunkableX & Charting w/ C3.js

Charting with Thunkable just got easier with the addition of the HTTPS POST method for the web viewer. We are finally able to pass data to webpages and not just API’s , making our apps even more powerful!


The following is an example of passing chart data to a static webpage allowing for dynamic chart creation using ThunkableX and C3.js charting library. We will be creating hypothetical scores for Thunkers, give the chart a random title, and show it all within a web viewer allowing for interactive graphs. 

See the live app here

_remixLink

 

First, we create the UI. This is made of a web viewer, button, and label (for debugging).

As you can see, this is a very simple example but it  could be incorporated into larger projects very easily. For example, you could remove the button to ‘Send Data’ and have this be an action that occurs in app, such as on screen load. 

 

Tho show the chart, you will need a few things. First to code your C3.js chart, at the most basic, in an HTML file and host it on a service like Github.com (mine’s there). 

 

See my chart code here!

Get your own hosting space here!

Now it’s time to add the code. For this example, we will use one variable only. This could be removed completely with some refactoring and replaced with a function that returns data. 

-Initialize an ‘app’ type variable named 

_trendLine.

I will utilize camelCase and  Leszynski naming conventions as this will help differentiate different components in the code and make it easier follow. 

all app components will use camelCase for naming

Next we need to create a list of X-values. Typically these data would come from your app and most often be associated with time of measurement or category if item being measured.  This example utilizes a list of popular users from the Thunkable Community! It takes a string of text, makes the string a list, then shuffles the list. Finally the function takes no arguments and only returns the  list of shuffled names. 

I can simply call this function like a variable. 

You can find this in the Functions sidebar after its creation
Notice, the names of all functions reflect what their purpose is

Now, we create data. Again, this is something that would typically come from your measurements and either local or cloud storage. For this example, randomized values will be created and stored in a list. The list of values will always equal the length of the list of X-values.

First create the createRandomValuesList function. This creates a list of values between 0-100. A random number is pulled from that list, and added to _randList. The number of times this occurs is based on the value sent in _listLenght obtained by asking for the length of the list returned by createXValues. 

Finally, this shuffled list of random values is returned to the function createData. createData will now return this list. 

This block now returns a random list of Y-values = length of the list of X-values

Before sending this data to be plotted on a chart there is one additional method added to this app. We will create a random phrase to send with the chart data as a chart title. 

 

The input list it put into a loop based on the input _phraseLength. Each time the loop is ran, a random word is pulled from _listOfWords and inserted into _newPhrase. When the loop is finished running, this method returns a string as the chart title. 

After the chart title has been made, the JSON body to be sent to the hosted webpage is constructed by joining them all together using ‘create object’ block with 4 inputs(parameters). The object is transformed into JSON with the ‘generate JSON from object’ block. And finally, the JSON is returned by calling createJSONBody method.

//This is an example of the JSON body being transmitted to the chart server
{
"data":[90,30,57,69,99,38,89,78,0,67,3,40,86,30,59,74],
"x":[" wei"," jared"," jimmy"," tatiang"," rollke"," darren"," manyone"," domhnall"," jane"," arun"," chris"," steven"," kartik","actech"," ting"," eionparkinson"],
"trend":["68.89","67.20","65.52","63.83","62.15","60.46","58.78","57.09","55.41","53.72","52.04","50.35","48.67","46.98","45.30","43.61"],
"title":"please call me sally"
}

Lastly, when we send the data, first we create the trendLine, then send the completed JSON body to the server where the chart is hosted. 

Assuming your chart is formatted correctly using HTML, CSS, and JavaScript. You should be able to easily send your data! We will use the method provided by @PaulMW from Thunkables development team. 

We copy only the columns and names configs into the “try” section of this snippet. We copy these because this is the data we want to load into the preconfigured chart located above in the code. 

We also create a var named titleName and make it equal to the object property of title and set data1(a default C3.js data name) to be the name of the phenomenon we are tracking.

Now, when we send data, and this pages recieves the data, it will load the data in to the preformatted chart. 

A complete example is below and can be found at the Github link posted at the top of the page. 

 

Happy Thunking! If you have any questions, post them below or find me on the forum!

<html>
  <head>
   
  <style>
  html, body {
  height: 100%;
  margin: 0; }
  div {
  height: 80%;
  width: 100%;
  }
  h6 {
  text-align: center;
  }
  #chart
  .c3-circles-trendLine {
  display: none;
  }
  .c3-axis .tick line {
  display: none;
  }
  .chart{
  width: 100%;
  height: 85%;
  }
  .c3-axis-y text {
  font-size: 10px; /* change the size of the fonts */
  }
  .c3-axis-x text {
  font-size: 10px; /* change the size of the fonts */
  }
   
  </style>
  <meta name=”viewportcontent=”width=device-width, initial-scale=1>
  <script src=”https://thunkable.github.io/webviewer-extension/thunkableWebviewerExtension.jstype=”text/javascript></script>
  <link href=”https://cdn.jsdelivr.net/npm/c3@0.7.15/c3.cssrel=”stylesheet>
  <script src=”https://d3js.org/d3.v5.min.js></script>
  <script src=”https://cdn.jsdelivr.net/npm/c3@0.7.15/c3.min.js></script>
  </head>
  <body>
  <!– messageDisplay comes from the thunkable app –>
   
  <h6> <span id=”messageDisplay></span></h6>
  <div id=”chart></div>
  <script>
  var chart = c3.generate({
  bindto: ‘#chart’,
  data: {
  x: ‘x’,
  columns: [
  [‘x’],
  [‘data1’],
  [‘trendLine’],
  ]
  },
  axis: {
  x: {
  type: ‘categories’,
  tick: {
  centered: true,
  outer: false,
  rotate: 45,
  multiline: false
   
  },
  padding: {
  left: 0,
  right: 0,
  }
   
  },
  y: {
  min: 0,
  max: 100,
  padding: 0
  }
  },
  legend: {
  show: false
  },
  tooltip: {
  grouped: false,
  position: (data, width, height, element) => {
  if (data[0].id === ‘data1’){ // <- change this value to suit your needs
  return { top: 40, left: 0 };
  }
  return { top: 1000, left: 0 };
  }
  }
  });
  chart.legend.show([‘trendLine’]);
  // when we get a message from the app, display it on the page
  // message should be a JSON string of a list of numbers
  //I think there is a way to change the legend titles. I dont want the trend title to show at all. EVER
  ThunkableWebviewerExtension.receiveMessage(function(message) {
  try {
   
  var messageList = JSON.parse(message);
  var titleName = messageList.title
  document.getElementById(‘messageDisplay’).innerHTML = “This chart is for “ + messageList.title;
  chart.load({
  columns: [
  [‘x’].concat(messageList.x),
  [‘data1’].concat(messageList.data),
  [‘trendLine’].concat(messageList.trend),
  ],
  names: {
  data1: titleName
  }
  });
  } catch (e) {
  console.error(“An error occurred. Message probably wasn’t a JSON string of an array of numbers”);
  }
  });
  </script>
  </body>
  </html>

15 thoughts on “ThunkableX & Charting w/ C3.js”

  1. hello there, thank you so much for this tip. This is what i was needed for. Any idea how to add this chart function to my current project?
    or do you suggest me to make another one?
    please do note that i’m a beginner, here’s my mail id ( immanuelkp2422@gmail.com)

    1. I think this is easy enough to add to your project at an intermediate level. It requires hosting the customized chart on a server. If you wanted to further customize mine, you would need to familiarize yourself with only a little bit of javaScript, CSS, and HTML. I also enjoy using quickchart.io as the service is super easy to utilize!

      1. Sir,i’m an electronics and communication student,i’m not good with coding, any idea or sugestions for me of how to implement this charting function in thunkable

    1. Hi mom7667, I’m sorry. I rearranged my repository recently. I have updated the example and the link.

      Thanks for pointing this out!

  2. I have been browsing online more than 3 hours today, yet
    I never found any interesting article like yours. It is pretty worth enough for me.
    In my view, if all web owners and bloggers made good content as
    you did, the internet will be much more useful than ever before.
    Wow, this paragraph is fastidious, my younger sister
    is analyzing these kinds of things, thus I am going to inform her.
    I visited several websites but the audio feature
    for audio songs existing at this website is in fact excellent.

    http://plumbing.com/

    1. Thank you for taking time to check this out!

      Any suggestions for what I could do next that you may find helpful or interesting?

Leave a Reply

Your email address will not be published. Required fields are marked *