Google Charts - How to line break axis label into two rows? (Multiple X Axes)
Asked Answered
T

5

13

I have my google line chart which looks something like this:

10|                        .
  |            .....----''' ''--.
09| .-----'''''                  ''-
  |                                 '.
08|                                   \
  |                                    '.
07|                                      '.
  |________________________________________________________
   2012/12/27 12:01    2012/12/26 12:22    2012/12/25 11:33

And I want it to look like this (notice the X-Axis label):

10|                        .
  |            .....----''' ''-.
09| .-----'''''                 \
  |                              '.
08|                                \
  |                                 '.
07|                                   '.
  |_______________________________________________
   2012/12/27          2012/12/26       2012/12/25
   12:01               12:22            11:33

I tried adding <br>, \n, and \r but no luck.

I looked through the documentation and the closest thing I found was hAxis.maxTextLines but there is no minTextLines options so I couldn't figure out how to force it. How can I do this?


UPDATE

It seems that this is possible when creating charts by linking to google. You just have to set the chxt variable with extra x values (however many more x axes you need): chxt=y,x,x. And then for each x axis, you set what the labels will be with the chxl variable. chxl=1:|2012/12/27|2012/12/26|2012/12/25|2:|12:01|12:22|11:33

For example:

http://chart.apis.google.com/chart?chxl=1:|2012/12/27|2012/12/26|2012/12/25|2:|12:01|12:22|11:33&chxr=0,7,10&chxt=y,x,x&chs=360x240&cht=bvg&chco=000000&chd=t1:9,10,7&cht=lc&chds=7,10

But the way I am creating my charts is through JavaScript. This way:

google.setOnLoadCallback(function(){
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Date');
  data.addColumn('number', 'Count');

  //Populate data

  new google.visualization.LineChart(document.getElementById('chart')).
    draw(data, {curveType: 'function',
                chartArea: {left: 70, top: 50, width: '100%', height: '85%'},
                width: 950, height: 800,
                interpolateNulls: true,
                pointSize: 5,
                legend: {position: 'none'},
                vAxis: {title: 'Count', viewWindow: {min: 7, max: 10}},
                hAxis: {title: 'Date', viewWindow: {min: 0, max: 3}}
               });
});

So I need to figure out a way how to do this using this format/API. How can I do it this way?

Tibbs answered 27/12, 2012 at 23:0 Comment(5)
@JSuar - You definitely earned the bounty but I am still trying to implement your solution.Tibbs
I hear ya. It's not the nicest solution. Here's a cleaned up version using your code above. The repeated x-axis data could also be collapsed into one array so you don't have to store it twice.Mistook
Did my solution above help? If so I can update my answer.Mistook
Yes it did. Go ahead and update your answer and I'll accept it.Tibbs
Answer updated. I'm glad I was able to help you find a solution.Mistook
M
8

Final Update

Working Example: http://jsbin.com/eyokec/1/ (edit version)

Well, as usual, some digging around yielded a few possible solutions. I was only successful at getting one to work but at least you know it's possible at this point. This answer from Insert Links into Google Charts api data? provided the working solution above.

  // Note: You will probably need to tweak these deltas
  // for your labels to position nicely.
  var xDelta = 35;
  var yDelta = 13;
  var years = ['2012/12/27|12:01','2012/12/26|12:22','2012/12/25|11:33','2012/12/24|11:33'];
  $('text').each(function(i, el) {
      if (years.indexOf(el.textContent) != -1) {
          var g = el.parentNode;
          var x = el.getAttribute('x');
          var y = el.getAttribute('y');
          var width = el.getAttribute('width') || 70;
          var height = el.getAttribute('height') || 35;
  
          // A "ForeignObject" tag is how you can inject HTML into an SVG document.
         var fo = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
          fo.setAttribute('x', x - xDelta);
          fo.setAttribute('y', y - yDelta);
          fo.setAttribute('height', height);
          fo.setAttribute('width', width);

          var body = document.createElementNS("http://www.w3.org/1999/xhtml", "BODY");
          var p = document.createElement("P");

          p.setAttribute("style", "font-size:.8em; font-family:Arial;text-align:center;color:#555;");
          p.innerHTML = el.textContent.replace('|','<br />');

          body.appendChild(p);
          fo.appendChild(body);
  
          // Remove the original SVG text and replace it with the HTML.
          g.removeChild(el);
          g.appendChild(fo);
      }
  });

The above code work but, understandably, is far from ideal. It's just a proof of concept that you can hopefully use. I saw other similar questions about updating SVG files but I couldn't get them to work. The above code might be able to update th SVG <text> nodes relying on <tspan> for multi-line support. I might try to get that to work at some point.

Tests

  • Chrome 23.0.1271.97 m: PASS
  • Firefox 17.0.1: PASS (more height needed)
  • IE9: FAIL (not sure why)

References


Update 0

Also, it appears that Google Image Charts API is now deprecated.

Important: The Image Charts portion of Google Chart Tools has been officially deprecated as of April 20, 2012. It will continue to work as per our deprecation policy.

So, although you can create the chart as an example of what you would like, it's possible that functionality was not brought over to Google Chart Tools.

That said, I did find this Chart Wizard that will help create the necessary JavaScript to embed your chart with the Visualization API.

Google Chart Image Example


Original

Doesn't appear possible. You could force it using hAxis.minTextSpacing. It works but that's certainly not the purpose of that configuration option. You could also pull the labels out and handle them via HTML, but I know that's not ideal either.

Mistook answered 31/12, 2012 at 20:41 Comment(0)
F
8

I used:

hAxis: {format:'MMM dd, yyy \nHH:mm'}

in my options array and Google API formatted it as

Mar 05, 2014
   16:00
Freya answered 6/3, 2014 at 20:3 Comment(4)
Why is this not the top voted answer!? Simple and to the point, add the line break where you need.Calcium
Great for Continuous X Axis (Date, Number...), but not suitable for Discrete X Axis (String) charts, like my one. :(Bavardage
Yes, this should be the solution to adding multiple lines in the axis labels. Thank you!Berstine
You may get a syntax error when using \n on certain charts when using an arrayToDataTable. Using back ticks "First Line\n Second line" will process this as a literal for the line break and give you two lines.Scrapple
D
3

Put a line break \n where needed e.g.

var data = [
    ["Days", "Pressure"],
    ["Mon\n16", 20],
    ["Tue\n17", 16],
    ["Wen\n18", 10],
    ["Thr\n19", 16],
    ["Fri\n20", 17]
];

Result example

Duotone answered 14/3, 2017 at 20:14 Comment(0)
M
0

Try to use "\\n" instead of "\n", its working fine to me.

Meenen answered 19/9, 2017 at 3:36 Comment(0)
X
0

In our case, it was also PHP single- vs double-quotes:

BAD date( 'Y\nM' )

BETTER date( "Y\nM" )

Xanthate answered 13/12, 2018 at 16:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.