jQuery 在加载时设置谷歌图表宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25523294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:07:24  来源:igfitidea点击:

Setting Google Charts width on load time

jquerychartsresponsive-designgoogle-visualization

提问by Louis

I have this google chart on a my website. It's a Scatter chart for now, but I would like the solution for all types of charts. If you load the site with a 700-px-wide window for example, the chart dimensions are not responsive: the chart is too wide. Below is the code I am using.

我的网站上有这个谷歌图表。现在是散点图,但我想要所有类型图表的解决方案。例如,如果您使用 700 像素宽的窗口加载站点,则图表尺寸没有响应:图表太宽。下面是我正在使用的代码。

HTML:

HTML:

<div id="chart_div"></div>

CSS:

CSS:

#chart_div {
    width:100%;
    height:20%;
}

JS:

JS:

var options = {
        title: 'Weight of pro surfer vs. Volume of his pro model',
        hAxis: {title: 'Weight (kg)', minValue: 53, maxValue: 100}, //55
        vAxis: {title: 'Volume (l)'}, //, minValue: 20, maxValue: 40},   //20
        legend: 'none',
           width: '100%',
            height: '100%',
           colors: ['#000000'],
           series: {
                  1: { color: '#06b4c8' }, 
              },
        legend: {position: 'top right', textStyle: {fontSize: 8}},
        chartArea: {width: '60%'},
           trendlines: { 0: {//type: 'exponential',
                    visibleInLegend: true,
                    color: 'grey',
                    lineWidth: 2,
                    opacity: 0.2,
                    labelInLegend: 'Linear trendline\n(Performance)'
                    } 
                }    // Draw a trendline for data series 0.
    };
    var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));        
    chart.draw(data, options);
    google.visualization.events.addListener(chart, 'ready', myReadyHandler());

    function myReadyHandler() {
        chartDrawn.resolve();       }

Edit: It seems that the div #chart_divhas the right size (the one that I set with css), but the chart inside this div doesn't adapt its size...it stays locked with See the image: enter image description here

编辑:似乎 div#chart_div具有正确的大小(我用 css 设置的那个),但是这个 div 内的图表不适应它的大小......它保持锁定 看图片: 在此处输入图片说明

回答by asgallant

Since the Visualization API charts are not responsive at all, you have to handle everything on your own. Typically, this means listening for the window "resize" event and redrawing your chart then (setting any dimensions as appropriate):

由于可视化 API 图表根本没有响应,因此您必须自己处理所有事情。通常,这意味着侦听窗口“调整大小”事件并重新绘制图表(根据需要设置任何尺寸):

function resize () {
    // change dimensions if necessary
    chart.draw(data, options);
}
if (window.addEventListener) {
    window.addEventListener('resize', resize);
}
else {
    window.attachEvent('onresize', resize);
}

回答by Olaf

For me, none of the above worked or they were too complex for me to give it a try.

对我来说,以上都没有奏效,或者它们太复杂了,我无法尝试。

The solution I found is simple and works perfectly. It involves just building a normal Google Chart, in my case a donut chart and then styling it using CSS.

我找到的解决方案很简单,而且效果很好。它只涉及构建一个普通的谷歌图表,在我的例子中是一个圆环图,然后使用 CSS 对其进行样式设置。

@media screen and (max-width: 1080px) {
    div#donutchart {
        zoom:0.6;
        margin-left:-16%;
    }
}

That's all. Of course you can set other values for max-width, zoom and margins to have your chart fit perfectly. My chart is 800x600 (you can see it here).

就这样。当然,您可以为 max-width、zoom 和 margins 设置其他值,以使您的图表完美契合。我的图表是 800x600(你可以在这里看到)。

回答by Azhar Ahmad

put width 100%of the chart and call the resize function as below

将图表的宽度设为100%并调用如下调整大小函数

$(window).resize(function(){
   yourCallingChartFunction();
});

回答by Csaba Toth

If you are using Twitter Bootstrap, since v3.2 you can leverage the embed-responsivestyles:

如果您使用 Twitter Bootstrap,从 v3.2 开始,您可以利用以下embed-responsive样式:

<div class="embed-responsive embed-responsive-16by9">
  <div id="chart_div" class="embed-responsive-item"></div>
</div>

Or if you want 4:3 aspect ratio:

或者,如果您想要 4:3 的纵横比:

<div class="embed-responsive embed-responsive-4by3">
  <div id="chart_div" class="embed-responsive-item"></div>
</div>

回答by Airon Roosalu

For responsive on load works:

对于响应负载工作:

#chart_div {
width:inherit;
height:inherit;
}

Altough it dosen't work when screen size changes during session.

尽管在会话期间屏幕尺寸发生变化时它不起作用。

回答by Akshay Chavan

I've added a HostListener which listens if there's any change in the window size. And there I set the height and width of the Google Chart as follows-

我添加了一个 HostListener 来监听窗口大小是否有任何变化。我在那里设置了谷歌图表的高度和宽度,如下所示 -

@HostListener('window:resize', ['$event'])
onResize(event) {
this.width = $(window).width() * 0.35;
this.height = $(window).height() * 0.3;
}

回答by Alex

A more efficient resizing snippet is below and re-usable;

下面是一个更有效的调整大小片段,可重复使用;

//bind a resizing function to the window
$(window).resize(function() {
    if(this.resizeTO) clearTimeout(this.resizeTO);
    this.resizeTO = setTimeout(function() {
        $(this).trigger('resizeEnd');
}, 500);
});
//usage of resizeEnd

$(window).bind('resizeEnd', function() {
    DoSomething();
});

回答by abdulmnam

The best solution is to change chart view as window resized:

最好的解决方案是在调整窗口大小时更改图表视图:

google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawChart); 
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Value');
data.addColumn('number', 'Sites');
data.addColumn({type: 'string', role: 'tooltip'});
data.addColumn({type: 'string', role: 'style'});
data.addRows([
['valueA', 57, 'Value A is 57', 'stroke-color: #000; stroke-width: 1'],
['valueB', 19, 'Value B is 19', 'stroke-color: #000; stroke-width: 1'],
['valueC', 25, 'Value C is 25', 'stroke-color: #000; stroke-width: 1']
]);
var options = {
colors: ['#fff2af'],
hAxis: {textPosition: 'none',textStyle:{color:'#fff'}},
vAxis: {gridlines: {color: '#fff'},textStyle:{color:'#fff'}},
legend: {position: 'none'},
backgroundColor: '#aadaff'
};
var chart = new google.visualization.ColumnChart(document.querySelector('#chart_div'));
chart.draw(data, options);
$(window).resize(function(){
var view = new google.visualization.DataView(data);
chart.draw(view, options);
})
}

回答by César León

Just don′t set the "width" property on the chart JS. That will set the width automatically on load time.

只是不要在图表 JS 上设置“宽度”属性。这将在加载时自动设置宽度。

Some code:

一些代码:

<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    // Load the Visualization API and the corechart package.
    google.charts.load('current', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.charts.setOnLoadCallback(drawChart);

    // Callback that creates and populates a data table,
    // instantiates the pie chart, passes in the data and
    // draws it.
    function drawChart() {

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        data.addRows([
            ['Mushrooms', 3],
            ['Onions', 1],
            ['Olives', 1],
            ['Zucchini', 1],
            ['Pepperoni', 2]
        ]);

        // Set chart options
        var options = {
            title: "Density of Precious Metals, in g/cm^3",
            height: 400
     //width: 1100, <--- DON'T SET THIS OPTION, it will be set automatically depending on the size of the container div
        };

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
</script>

<!--Div that will hold the pie chart-->
<div id="chart_div" class="mt-3" style="height: 400px; width: 100%; border: 1px solid #CCCCCC"></div>

回答by mzografski

I found this Code pen example usefull: Code pen example of Google Charts ResponsiveThey do redraw the graph on window resize using jQuery:

我发现这个代码笔示例很有用: Google Charts Responsive 的代码笔示例他们确实使用 jQuery 在调整窗口大小时重新绘制图形:

$(window).resize(function(){
   yourCartdrawChartfuntion();
});