Using JSON to import categorical data from SQL into C3.js

I am currently working on creating dynamic column graphs in MVC by utilizing C3 Charts. Although I have successfully retrieved data from the database using AJAX/JSON, I am facing challenges in binding the X-Axis categories along with the Y-Axis coordinates using the JSON property of C3.

My goal is to dynamically build column charts where student marks from multiple years are displayed as (Year 1: 50), (Year 2: 100), and so forth. The X-Axis will represent the year category, while the Y-Axis will display the numeric marks. These combinations vary based on user requirements and are sourced from two columns in the database with multiple rows.

Issues I am encountering:

  1. When specifying different data types for keys, the non-numeric part (category) appears as a separate series instead of being integrated into the chart.

  2. The X-Axis displays whole numbers based on visible columns, whereas I aim to show actual category names.

This is my current approach, inspired by Daniel's method mentioned here (https://groups.google.com/d/msg/c3js/RV1X18GZoGY/-p39m9Ngt-gJ)

    $.ajax({
    url: <Method in Controller here>,
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(parameters),
    success: function (data) {
            var myData = jQuery.parseJSON(data);
            var testJson = $.map(myData, function (item) {
                return {
                    Year: item.Year,
                    Marks: item.Marks

                }
            });

            var chart = c3.generate({
                bindto: '#chart',
                size: {
                    width: 800
                },
                data: {
                    json: testJson,

                    mimeType: 'json',
                    keys: {
                        value: ['Marks']
                    },

                }
            });
    }
});

Your assistance in resolving these issues would be greatly appreciated. Thank you!

Edit: Ultimately, I envision the data to appear like this: Sample Chart

Answer №1

If you want to create a bar chart, consider using the code snippet below:

var data =  [
                   { year: 1, marks: 50 },
                   { year: 2, marks: 70 },
                   { year: 3, marks: 75 },
                   { year: 4, marks: 45 },
                ];

// The variable "chart" will be associated with an element having id = "chart"
var chart = c3.generate({
    data: {                
        type : 'bar',
        json: data,
        keys: {
            x: 'year',
            value: ['marks']
        }
    },
    size: {
        width: 400,
    },
    axis: {
        x: {
            type: 'category'
        }
    },
    bar: {
        width: {
            ratio: 0.5
        }
    }
});

The output of this code can be seen here:

https://i.sstatic.net/XAg7l.png

To view a live example, check out this JSBin link: Bar Chart Example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing a specific item from a panel using JavaScript

Here is the code I have created that functions in a specific way. When a user selects a checkbox, it adds the selected item's name and price to calculate the subtotal based on the quantity inputted by the user. Now, when a user deselects a checkbox, ...

What is the process of converting a java object into a string?

I have been tasked with transitioning a legacy API to a microservice architecture. The current API encodes a java object into a base64 String using the following code: public String serialize() throws Exception { String mementoXml = null; Document ...

Convert CSV data to JSON/dictionary format while adding extra keywords or organizing the data

I'm looking to convert a .csv file into JSON or dictionary format. The data currently looks like this: cat1,cat2,cat3,name 1,2,3,a 4,5,6,b 7,8,9,c My current approach involves using code similar to the following (along with importing pandas.df for g ...

Exploring the wonders of HTTP requests through pure pipes in Angular 5

I've been working on a pipe that converts currency values from one to another by making an HTTP call. The idea is to pass in the source and destination currencies as parameters. @Pipe({ name: "currencyConverter" }) export class CurrencyConverterP ...

Angular.js: Navigating through HTML content

I am attempting to display a list of HTML data using angular.js and would like to implement ngInfiniteScroll. Here is the template I created: update: <div class="scroll" id="antTalkList" talk-type="total" view-type="total" infinite-scroll=' ...

Ways to get to the bottom in a React component using a button

I've been struggling to automatically scroll the user to the bottom of the page when they click on a button. Despite my best efforts, I haven't been able to find a solution. Can someone please assist me in achieving this goal? Thank you ...

Easily Update Your Div Content by Simply Clicking a Single Link/Button

I am in need of assistance here. My goal is to display dynamic content within a div. Below you will find the code I currently have: <script type="text/javascript"><!-- function AlterContentInContainer(id, content) { var container = documen ...

How can JavaScript determine if this is a legitimate JS class?

I'm currently in the process of converting a React.js project to a next.js project. In my project, there's a file named udf-compatible-datafeed.js. import * as tslib_1 from "tslib"; import { UDFCompatibleDatafeedBase } from "./udf-compatibl ...

Unable to display information in jvectormap using json format

For the past 48 hours, I've been struggling to find a solution to a persistent issue I'm facing. The problem arises when I try to integrate data from an MSSQL database into a map using the jvectormap plugin for Turkey. Despite dynamically assigni ...

I am in need of the edit/add data from jqGrid in x-www-form-urlencoded format, but I actually require it in application

Currently, I am working on integrating my jqGrid with a Java Rest service. Whenever I send the edit or add data from jqGrid to my rest service for further processing related to Database CRUD operations, it gets received in this format: "nume=Alin&pren ...

Embed the anchor tag within a JQuery JSON structure

I am using jQuery syntax to retrieve a JSON list from a database. Here is the code snippet: $(document).ready(function () { //function to fetch user-input result $("#btnsearch").click(function() { $("#posting").html(""); //showing ...

Employing Browserify within specific files in a directory as part of a Gulp workflow

When working with Browserify, the usual approach to combine multiple files involves running a task like this: gulp.task('build-tests', function() { var b = browserify({ entries: ['./lib/some_specs.js', './lib/s ...

Cannot load the next page using jQuery ajax

I am working on a project with an index.html file that includes a nav menu, header, footer, and a div.content where jQuery is used to parse the html of page1.html. Initially, page1.html loads perfectly. However, I encountered an issue when trying to imple ...

What could be causing my chosen value to remain unchanged after being copied from a controller?

I am struggling with controlling a <select> element using both ng-model and ng-options: <select ng-model="user.option" ng-options="value.label for (key, value) in data.options"> <option value="">Select value</option> ...

Ways to substitute PHP functions using AJAX

I'm a beginner with AJAX. How do I replace the initial PHP function after an AJAX action is executed? It seems that the page does not refresh after the action takes place. Below is the code: Javascript function set_ddm(another_data) { var resul ...

Unable to utilize jQuery within the NetBeans IDE

Whenever I try to include a jQuery file in Netbeans like this: <script type="text/javascript" src="js/jquery-1.3.2.js"> my code doesn't seem to work. However, when I use the following method: <script type="text/javascript" src="http://ajax ...

Utilizing Vuejs to initiate a GET request using a method

Currently, I am working on enhancing the functionality of a GET request in Vue. My goal is to attach the request sending action to the form's submit button and also include a parameter from a text field within the form. HTML <html> <head> ...

Why is it that using "return false" does not stop the page from reloading when clicked?

I've attempted using this code, but it doesn't seem to prevent the page from reloading when the onclick function is triggered. What am I missing here? Could this be a problem related to browser compatibility? function track_specs() { $('b ...

Modify airflow environment variables by running commands

I have a variable named BLUE_APPLE in my airflow environment. Currently, I am logged into the airflow web server. airflow variables --get BLUE_APPLE When I run the above command, it shows: { "title": "Sample Konfabulator Widget" ...

What are the steps to run a webpack project without relying on webpack-dev-server?

I've been working on hosting my project on GitHub pages by creating a /doc file and placing all my HTML, CSS, and JS there. If you're interested, you can check out my project here: https://github.com/mattfrancis888/the_movie_db The only way I&a ...