开发者

How to set Google Charts legend width in JavaScript?

开发者 https://www.devze.com 2023-03-23 22:32 出处:网络
I am generating this Go开发者_如何学Cogle Line Chart using the Google JS API. As you can see, the labels are very narrow. How do I make it so that the whole label text is visible?

I am generating this Go开发者_如何学Cogle Line Chart using the Google JS API. As you can see, the labels are very narrow. How do I make it so that the whole label text is visible?

How to set Google Charts legend width in JavaScript?


Here are some samples based on the google code playground line charts. Adjusting the chartArea width option gives more space for labels:

new google.visualization.LineChart(document.getElementById('visualization')).
    draw(data, {curveType: "function",
                width: 500, height: 400,
                vAxis: {maxValue: 10},
                chartArea: {width: '50%'}}
        );

If it's an option, you could also position the labels beneath the chart, which gives considerably more space:

new google.visualization.LineChart(document.getElementById('visualization')).
    draw(data, {curveType: "function",
                width: 500, height: 400,
                vAxis: {maxValue: 10},
                legend: 'bottom'}
        );


Expanding the chartArea option to a width of 100% solved the problem for me. Contrary to the documentation, the chartArea does include the legend. I used a PieChart but the same option is available for the LineChart.

var options = {'title':title,'width':w,'height':h,'chartArea':{left:0,top:10,width:"100%"}};
var chart = new google.visualization.PieChart(document.getElementById(chartDiv));
chart.draw(data,options);

Reference.


None of the previous answers worked well for me. Setting width to less than 100% centers the plot area and leaves too much unused space on the left. Setting it to 100% is not a solution either.

What worked well - see live working fiddle - is setting the right value to accommodate the legend, then adjusting the left value eventually, for the Y axis title and labels. The plot area width will adjust automatically between these two fixed margins:

var options = {
   ...
   legend: { position: 'right' },
   chartArea: {
      right: 130,   // set this to adjust the legend width
      left: 60,     // set this eventually, to adjust the left margin
   },
   ...
};


There is an option in legend.textStyle we can customize legend text styles inside google charts

var options = {
                legend: { textStyle: { fontSize: 78  //size of the legend 
                } }
              }


You need to make the chart wider or your labels shorter.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号