以下是我使用 PlotlyJS 绘制响应图的 js
代码。
var trace1 = {
x: ['Category A', 'Category B', 'Category C', 'Category D ', 'Category E', 'Category F', 'Category G', 'Category H'],
y: [20, 14, 23, 20, 14, 23, 34, 26],
marker: {
color: ['rgba(0,152,212,0.5)', 'rgba(0,152,212,0.5)', 'rgba(0,152,212,0.5)', 'rgba(0,152,212,0.5)', 'rgba(0,152,212,0.5)', 'rgba(0,152,212,0.5)', 'rgba(0,152,212,0.5)', 'rgba(0,152,212,0.5)']
},
name: 'Item 1',
type: 'bar'
};
var trace2 = {
x: ['Category A', 'Category B', 'Category C', 'Category D ', 'Category E', 'Category F', 'Category G', 'Category H'],
y: [12, 18, 29, 12, 18, 29, 24, 22],
marker: {
color: ['rgba(0,152,212,1)', 'rgba(0,152,212,1)', 'rgba(0,152,212,1)', 'rgba(0,152,212,1)', 'rgba(0,152,212,1)', 'rgba(0,152,212,1)', 'rgba(0,152,212,1)', 'rgba(0,152,212,1)']
},
name: 'Item 2',
type: 'bar'
};
var trace3 = {
x: ['Category A', 'Category B', 'Category C', 'Category D ', 'Category E', 'Category F', 'Category G', 'Category H'],
y: [12, 18, 29, 12, 18, 29, 24, 22],
marker: {
color: ['rgba(0,54,136,1)', 'rgba(0,54,136,1)', 'rgba(0,54,136,1)', 'rgba(0,54,136,1)', 'rgba(0,54,136,1)', 'rgba(0,54,136,1)', 'rgba(0,54,136,1)', 'rgba(0,54,136,1)']
},
name: 'Item 3',
type: 'bar'
};
var data = [trace1, trace2, trace3];
var layout = {
barmode: 'stack',
};
Plotly.newPlot('myDivPlotly', data, layout);
// code to make plotlyjs responsive
(function() {
var d3 = Plotly.d3;
var WIDTH_IN_PERCENT_OF_PARENT = 100,
HEIGHT_IN_PERCENT_OF_PARENT = 100;
var gd3 = d3.selectAll(".responsive-plot")
.style({
width: WIDTH_IN_PERCENT_OF_PARENT + '%',
'margin-left': (100 - WIDTH_IN_PERCENT_OF_PARENT) / 2 + '%',
height: HEIGHT_IN_PERCENT_OF_PARENT + 'vh',
'margin-top': (100 - HEIGHT_IN_PERCENT_OF_PARENT) / 2 + 'vh'
});
var nodes_to_resize = gd3[0]; //not sure why but the goods are within a nested array
window.onresize = function() {
for (var i = 0; i < nodes_to_resize.length; i++) {
Plotly.Plots.resize(nodes_to_resize[i]);
}
};
})();
以下是我的 HTML
代码,用于在 Bootstrap 卡片中绘制 plotlyJS 图表。
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="card">
<h5 class="card-header">Featured</h5>
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card">
<h5 class="card-header">Featured</h5>
<div class="card-body">
<div class="responsive-plot" id="myDivPlotly">
</div>
</div>
</div>
</div>
</div>
图表现在可以响应,但问题是该图上方和下方有很多空白空间。如何移除绘图周围的空白空间或降低卡片的高度。
请帮忙。谢谢。
最佳答案
您必须做一些小事来删除底部的空白区域。但是在顶部边缘有一个隐藏的绘图栏,只有当鼠标悬停在它上面时才会显示。 您必须在 .js 文件中更改这些内容。
var gd3 = d3.selectAll(".responsive-plot")
.style({
width: 'fit-content',
'margin-left': (100 - WIDTH_IN_PERCENT_OF_PARENT) / 2 + '%',
height: 'fit-content',
'margin-top': '0vh'
});
关于javascript - Bootstrap 卡片中的响应式 PlotlyJS 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57070807/