What is the best way to incorporate multiple vertical axes (y) into a Google chart?

I created a line graph with 2 lines that refresh every 5 seconds.

Now, I'm trying to add dual vAxis on the left and right side.

However, I can't seem to display the vAxis title. How can I fix this?

Here is the chart option that I added:

This graph fetches data from a servlet and displays the count.

Please advise if there is a simple way to correct the code.

Thank you.

var chartOption1 = function(target, name, namename){
        var d=new Date();
        this.name = name;
        this.name2=namename;
        this.target = target;
        this.data = null;
        this.chart = null;
        this.options = {
          title:d.getFullYear()+'년 '+(1+d.getMonth())+'월 '+d.getDate()+'일 '+'금일 누적 Flow 유입 개수',
          legend: { position: 'top' },
          titleTextStyle:{
                fontSize: 20,
                bold: true
            },
            series:{
                0:{targetAxisIndex:0},
                1:{targetAxisIndex:1}

            },
          vAxis:  {0:{precision:0, baseline:0, title:'Normal Flow 개수', minValue:0, maxValue:100, format:'0'},
                   1:{precision:0, baseline:0, title:'Anomaly Flow 개수', minValue:0, maxValue:100, format:'0'}
          },
          hAxis: {
              title:'기준 시간',
            textStyle: {
              fontSize: 11
            }
          },
          colors: ['#1cc88a', '#e74a3b'],
          animation: {
            duration: 500,
            easing: 'in',
            startup: true
          }
        }

    }
      var new_option1 = new chartOption1('chart','Normal Flow', 'Anomaly Flow');


      function drawChart1(option1) {
        var o1 = option1;
        if(o1 != null){
          //Process only when it's the initial value
          if(o1.chart == null || o1.data == null){
            o1.data = new google.visualization.DataTable();
            o1.data.addColumn('string', 'time');
            o1.data.addColumn('number', o1.name);
            o1.data.addColumn('number', o1.name2);
            o1.data.addRow(['', 0, 0]);
            o1.chart = new google.visualization.ColumnChart(document.getElementById("in_flow_daily"));
          }
          o1.chart.draw(o1.data, o1.options);
        }
      }

      function animateRenewal1(option1){
        var o1 = option1;
        if (o1.data.getNumberOfRows() >= 8) {
          o1.data.removeRow(0);
        }

        var value1 = $.ajax({
            type:'POST',
            url:"/Flow_servlet/normalflow_count_daily.do",
            data: {
                now :getNowTime1(),
                nowend:getNowTimeend1()

            },
            cache:false,
            async:false
        }).responseText;

        var value1value1 = $.ajax({
            type:'POST',
            url:"/Flow_servlet/anomalyflow_count_daily.do",
            data: {
                now :getNowTime1(),
                nowend:getNowTimeend1()

            },
            cache:false,
            async:false
        }).responseText;

        value1=parseInt(value1);
        value1value1=parseInt(value1value1);
        o1.data.insertRows(o1.data.getNumberOfRows(), [[getNowOnlyTime1(), value1, value1value1]]);
        drawChart1(o1);
        window.addEventListener('resize', o1, false);
      }

      setInterval(function(){ //Executes every 50 seconds
        animateRenewal1(new_option1);
        drawChart3();
        drawChart2();
        drawChart4();
      }, 5000);

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

Answer №1

simply adjust the y-axis option that is being utilized.

modify --> vAxis

to --> vAxes

(adding an e)

vAxis controls formatting for all y-axes, without specific index keys ({0: ..., 1: ...})

opt for vAxis for uniform application of values to all y-axes

for custom styling of individual y-axes, utilize vAxes

review the operational code snippet below...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'x');
  data.addColumn('number', 'Normal Flow');
  data.addColumn('number', 'Anomaly Flow');
  data.addRow(['11.21.55', 12, 10]);
  data.addRow(['11.22.0', 12, 10]);
  data.addRow(['11.22.5', 12, 10]);

  var d = new Date();

  var options = {
    title: d.getFullYear()+'년 '+(1+d.getMonth())+'월 '+d.getDate()+'일 '+'금일 누적 Flow 유입 개수',
    legend: {
      position: 'top'
    },
    titleTextStyle:{
      fontSize: 20,
      bold: true
    },
    series:{
      0:{targetAxisIndex:0},
      1:{targetAxisIndex:1}
    },
    vAxis:  {precision:0, baseline:0, minValue:0, maxValue:100, format:'0'},
    vAxes:  {
      0: {title:'Normal Flow 개수'},
      1: {title:'Anomaly Flow 개수'}
    },
    hAxis: {
      title:'기준 시간',
      textStyle: {
        fontSize: 11
      }
    },
    colors: ['#1cc88a', '#e74a3b'],
    animation: {
      duration: 500,
      easing: 'in',
      startup: true
    }
  };

  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, options);
});
html, body {
  height: 100%;
  margin: 0px 0px 0px 0px;
  overflow: hidden;
  padding: 0px 0px 0px 0px;
}

#chart_div {
  height: 100%;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

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

What advantages does Angular Service offer when gathering information compared to utilizing only $http?

Comparing Two Approaches: Approach A. Creating app module Using a service to store model data Implementing a controller to retrieve data from the service File 1: Users.js: angular.module('users', []); File 2: userService.js: angular ...

Add-on or code snippet for Node.js that allows for optional regex groups

Strings in Sequence line 1 = [A B C] line 2 = [A C] line 3 = [B C] Regular Expression /\[?(?<groupA>[A])?(?:[ ]*)?(?<groupB>[B])?(?:[ ]*)?(?<groupC>[C])\]/gm Is there a way to achieve the desired output using a plugin or spe ...

What is the best way to divide multiple event handlers in jQuery?

Is there a way to organize the code below more effectively by splitting the multiple events into separate lines? $document.find('body').on( 'click dblclick mousedown mousemove mouseout mouseover mouseup mousewheel keydown keypress keyup ...

Guide to setting up an automated process in PHP

When setting up a tournament interface on my page: Users utilize functions like fopen() and fwrite() to create tournaments. The created tournaments must only start after a specific time, for example, 1 hour. This delay allows other users to join the tour ...

The received URL from the POST request in React is now being opened

After completing an API call, I successfully received the correct response in my console. Is there a way to redirect my React app from the local host to the URL provided (in this case, the one labeled GatewayUrl under data)? Any assistance would be greatly ...

Storing various duplicates of items in local storage

Looking for help with storage settings in HTML/JavaScript as I work on a mobile not taking app using Phonegap. My goal is to allow users to input a note name and content, save them into a jquery mobile list, and see them on the home screen. However, I&apos ...

There was an issue locating the moment/ts3.1-typings/moment module

Encountering an ERROR after updating Angular version: Could not resolve moment/ts3.1-typings/moment in node_modules/ngx-daterangepicker-material/ngx-daterangepicker-material.d.ts ...

Add a fresh text field with the click of a button and delete it with another button in Laravel 4

My form includes two fields: phone and email, as shown in the image below. By clicking on the plus button, I would like to add an additional text field to the form below the button. Similarly, by clicking on the minus button, I want to remove the text fie ...

Revealing elements with AngularJS ng-show directive prior to concealing them

Currently, I am in the process of implementing a slide effect for bootstrap badges to showcase hierarchical data relationships using AngularJS. My goal is to have a slider-effect that smoothly reveals new sub-categories while concealing previously open su ...

Issue with locating JavaScript controller in Angular HTML file [Node.js/Angular]

Here are all the files and folders in my project located within the same directory. If you want to check out the project on Github, you can find it here: https://github.com/JohnsCurry/learnAngular. Just to confirm, they are all in the same folder. Unfortu ...

ReactJS tables that can be filtered and sorted

Within my component's state, there exists an array named 'contributors'. Each element within this array is an object containing various properties. My goal is to present this data in a table format, with the added functionality of sorting an ...

Ways to enable an Angular 5 web application to launch in multiple tabs within a single browser

Is there a way to open an Angular 5 app in multiple tabs of Chrome? Are there any methods or caching processes that can assist with this task? ...

Discover a simple method for comparing JSON responses and UI elements by utilizing two arrays in a for loop within your Cypress automation tests

I am in need of assistance where I must compare JSON response data with UI elements. If matching elements are found, the task is to print them in a log file. This requires checking all JSON responses using a for loop. Can someone provide me with Cypress Ja ...

Create a shape using a series of points without allowing any overlap between the lines

JS fiddle There is an array of coordinates that gets populated by mouse clicks on a canvas. var pointsArray = []; Each mouse click pushes x and y values into this array using a click event. pointsArray.push({x: xVal, y: yVal}); The script iterates thr ...

Can someone explain why my search input's sync function is being triggered twice?

Within my CodePen project at https://codepen.io/aaronk488/pen/MWbKNOq?editors=1011, I am facing an issue where my sync function search is being called twice without a clear reason. Even though I managed to resolve this by adding a conditional statement in ...

dispatch a WebSocket message within a route using Express.js

The Objective: Imagine a bustling marketplace with multiple shops. I'm working on a dedicated page localhost:3000/livePurchases/:storeId for shop owners to receive real-time notifications whenever they make a new sale. https://i.stack.imgur.com/VdNz ...

Tips for adapting my custom input component for compatibility with vee-validate?

I recently developed an input component for my Vue project and integrated it within my forms. My aim is to implement vee-validate for validating the inputs. Initially, I attempted to validate my component like any regular input field. However, upon encoun ...

When a user clicks anywhere on the website, the active and focused class will be automatically removed

I'm currently working with Bootstrap tabs on my website. I have three tabs, and when a user clicks on one, the active and focus classes are added to indicate which tab is selected. However, I've encountered an issue where clicking anywhere else ...

Sync issues observed with jQuery slide animations

I am currently utilizing a carousel slider that includes text content. When the user clicks on the 'next' button, the .carousel-text div slides up to hide the text, the carousel then moves to the next slide, and finally the .carousel-text on the ...

Tips for obtaining the correct Javascript output for the number pyramid

I'm currently in the process of creating a half pyramid of numbers, but I'm facing an issue with getting the output to show the total for each line while maintaining everything except the * sign between the numbers. If anyone is able to offer som ...