Display solely the dates on the timeline chart of Google charts

I am facing an issue with my timeline chart script that I am using. The code snippet is as follows:

      google.charts.load("current", {packages:["timeline"],'language': 'pt'});
        google.charts.setOnLoadCallback(drawChart);
        function drawChart() {


            var jsonData = $.ajax({
                url : 'Consulta/getDados',
                dataType : 'json',
                async: false

            }).responseText;

            //console.log(jsonData);

            var container = document.getElementById('chart');
            var chart = new google.visualization.Timeline(container);
            var dataTable = new google.visualization.DataTable(jsonData);
            google.visualization.events.addListener(chart, 'ready', afterDraw);

            var options ={
              timeline: { showRowLabels: false},
              alternatingRowStyle: true,
               hAxis: {
                format: 'dd.MM.yyyy',
                }
            };

            chart.draw(dataTable,
                {
                    width: '100%',
                    height: 1000
                });
        }

The data for the graph is fetched from a database and displayed on it. The 'afterDraw' function is used to adjust the x Axis position on the graph. Although my focus is not on this function, I will include it just to eliminate any doubt about it being the cause of the problem.

   function afterDraw() {
        var g = document.getElementsByTagName("svg")[0].getElementsByTagName("g")[1];
        document.getElementsByTagName("svg")[0].parentNode.style.top = '45px';
        document.getElementsByTagName("svg")[0].style.overflow = 'visible';
        var height = Number(g.getElementsByTagName("text")[0].getAttribute('y')) + 20;
        g.setAttribute('transform','translate(0,-'+height+')');
        g = null;
    }

The issue arises when I select a date range of less than 6 days. In this case, the graph stops displaying dates on the x axis and starts showing hours instead.

This is how it should look: Desired result

However, when the date range is less than 6 days: Undesirable behavior

I have attempted to use ticks and the hAxis property in the options but without success. How can I ensure that only days are shown on the x axis, even if the date range is less than a week?

Answer №1

If you want to display only the date and customize the appearance of the chart, use the following code snippet. Make sure to replace the options section in your existing code:

 var options = {
            timeline: {
                showRowLabels: false
            },
            avoidOverlappingGridLines: false,
            hAxis: {
                format: 'd MMM',
                gridlines: {
                    count: -1
                },
                minValue: startDate,
                maxValue: endDate,
                ticks: generateUniqueTicks(startDate, endDate)
            },
            chartArea: {
                width: '90%',
                height: '80%'
            }
        };

        chart.draw(dataTable, options);
        afterDraw();

Add the following functions to your code: afterDraw and generateUniqueTicks

function generateUniqueTicks(startDate, endDate) {
        var ticks = [];
        var currentDate = new Date(startDate);
        while (currentDate <= endDate) {
            ticks.push(new Date(currentDate));
            currentDate.setDate(currentDate.getDate() + 1); // Increment by one day
        }
        return ticks.map(date => {
            return {
                v: date,
                f: date.toLocaleDateString('en-GB', {
                    day: '2-digit',
                    month: 'short',
                    year: 'numeric'
                }) // Custom date format
            };
        });
    }

    function afterDraw() {
        var svg = document.getElementsByTagName("svg")[0];
        if (!svg) return;
        var g = svg.getElementsByTagName("g")[1];
        svg.style.overflow = 'visible';
        svg.parentNode.style.top = '45px';
        if (g) {
            var height = Number(g.getElementsByTagName("text")[0].getAttribute('y')) + 20;
            g.setAttribute('transform', 'translate(0, -' + height + ')');
        }
    }

    window.addEventListener('resize', drawChart);

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

Using only if-else statements and else-if conditions in JavaScript, arrange four numbers in order

How can I arrange 4 numbers in ascending order using only if-else and else-if statements in JavaScript without utilizing the sort function? ...

Ways to Implement Named Module Exports in Node.js Version 16 Application

Currently, I am working with Node 16.3.0 and Express 4.17.1 (although the Node version is open to change) In my project, I have a file named session.js structured as follows: // session.js exports.fetchUserId = async function(token){ ... } exports.sav ...

Ways to display Multiple Images in a Listview

I am facing an issue where multiple images are displayed inside a List View Item perfectly, but after scrolling the page, duplicate images appear within the list view item. I am dynamically creating ImageView and adding it to a Linear Layout. How can I fix ...

Utilizing Angular to Fetch JSON Data from a Server

I am currently retrieving data from a JSON file that resides on a server and is updated regularly. It's crucial for me to access this JSON content in order to consistently showcase the most recent information on my website. At present, I have stored ...

Can anyone recommend a reliable JavaScript library for creating resizable elements?

I am looking to incorporate resizable functionality for a textarea. While I have experimented with jQuery UI's "resizable" feature, it doesn't quite meet my needs. I appreciate jQuery, but the resizable option falls short in allowing me to resize ...

Exploring a JavaScript function that triggers another function to create a new object - Utilizing Sinon and Mocha for testing purposes

I am currently working on a nodejs application where I need to write a test for a function that invokes another function to create a new object, and then calls a method of that object. Below is the code in service.js that I am trying to test; // servic ...

Stop angular schema form's destroyStrategy from deleting any data

After upgrading my Angular app from version 0.8.2 to 0.8.3 of Angular Schema Form (ASF), a significant bug emerged. The application features multi-page forms that utilize prev/next buttons for navigation. A condition is implemented to display only relevan ...

Use jQuery eq() to populate a group of text fields with data stored in localStorage

In my project, I have a series of text areas that are configured to save their content in localStorage for persistence. As I attempt to retrieve and reassign these values when the browser reloads, I encounter an issue with the following code snippet. When ...

What is the method for creating a regex pattern that captures a single symbol under specific conditions?

I am in need of a JavaScript regex that can specifically select a single character with one condition: it must not be followed or preceded by a particular specified character. The target character is /, but I want to select it only if it is not immediatel ...

Dynamically delete a property from a JSON object

I am currently working on a task that involves removing properties from a JSON object. I need to create a system where I can specify an array of locations from which the fields should be redacted. The JSON request I am dealing with looks like this: { "nam ...

Error: The "map" property cannot be read if it is undefined in a Django and React application

While I was following the react and django tutorial, I encountered an issue when I added some code for concern with. The error message 'Cannot read property 'map' of undefined' keeps getting thrown. The error location is pointed out ...

What is the best way to verify Vue.js fields that have been pre-filled from a database source?

Looking to validate the inputs from a form using vuejs. Also, if the data is pre-populated, I want the inputs to switch to readonly mode. <input type="number" name="cf_962" class="form-control" v-model="fillProfile.cf_962" step="0.1" :readonly="(fillPr ...

Using JSON decoding within a CGridView

Currently, I am utilizing a cgridview (Yii) to showcase a lunch along with its users. The users are stored in JSON format in the database, and I am seeking a way to decode and display them within the same view as the rest of the table. Here is the code sn ...

Tips for populating a dropdown list with data from the backend and selecting the desired value using Angular

I am currently working on an Angular 8 application that utilizes Material design. My goal is to populate a dropdown list with data retrieved from the backend. The API call code snippet is as follows: returnQrCodes$ : Observable<QRCodeDefinitionSelect ...

Show information - press the button on the current PHP page

After successfully reading files via PHP from a directory and dynamically creating a drop-down menu to view the file content, I have a query. Is there a way to display the text files' content on the same page without calling another PHP page? I know t ...

Exploring the method of updating functions in Firebase Admin SDK through spying

Is there a way to monitor the update function in Firebase Admin SDK as shown below? yield admin.database().ref('ref').update(obj) I attempted the following without success: const databaseStub = sinon.stub(); const refStub = sinon.stub(); const ...

Adjust the size of the plane in Three.js to match the entire view

English is not my strong suit, as I am Japanese. I apologize for any confusion. Currently, my focus is on studying Three.js. I aim to position a Plane directly in front of the camera as the background. My goal is to have the Plane background fill the en ...

Effortlessly fill dropdown menus with data from JSON files

I've been using this jQuery code successfully, but I recently needed to add 3 more field columns to the JSON. My goal is to have the HTML select drop-downs dynamically change based on the data from the previous drop-down. Additionally, my current jQue ...

Double Assignment in JavaScript

Can you explain the concept of double assignment in ExpressJS and its functionality? An illustration is provided below using a code snippet from an ExpressJS instance. var server = module.exports = express() ...

Struggling with implementing material-ui icons and facing a blank screen

Having trouble displaying material-ui icons on my website. Whenever I use them, a white screen appears. I have tried running the following commands: npm install @mui/material @emotion/react @emotion/styled npm install @material-ui/icons I also visited t ...