如何在一个html页面上应用两个svg?

时间:2019-06-20 19:50:02

标签: javascript html css d3.js svg

所以我有2个图:线图和箱线图,但我希望线图旁边的箱线图位于下面。如何制作使其位于折线图旁边?任何想法表示赞赏。谢谢!

我尝试使用2种不同的SVG,但是没有用。这是我的代码:http://next.plnkr.co/edit/mWGOEy0GHp1olZgNgtpA?preview

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.line {
    fill: none;                 
  stroke: url(#grad);    
  stroke-width: 2px; 
}
.zoom {
  cursor: move;
  fill: none;
  pointer-events: all;
}

</style>
<svg width="900" height="700">  
</svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

var svg = d3.select("svg"),
    margin = {top: 90, right: 50, bottom: 100, left: 40},
    margin2 = {top: 630, right: 50, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    height2 = +svg.attr("height") - margin2.top - margin2.bottom;

...more code 
</script>

//end of line graph 

//beginning of boxplot
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<div id="svg2"></div>

<!-- To use the monochrome scale -->
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>

<!-- Tooltip style -->
<style>
.tooltip {
  background-color: black;
  border: 1px black solid;
  display: inline-block;
  border-radius: 5px;
  padding: 15px;
  min-width: 1000px;
  text-align: left;
  color: white;  
}
</style>

<script>
// set the dimensions and margins of the graph
var margin = {top: 70, right: 30, bottom: 50, left: 80},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

...more code, end of boxplot
</script>

This is what it looks like right now

2 个答案:

答案 0 :(得分:1)

有两种基本的HTML元素-块元素和内联元素。块元素(例如div的元素)会将紧随其后的元素下推到下一行。内联元素(例如span的元素)没有,而是与其后的内容共享一行,除非它们两个都没有足够的空间。

如果您希望块元素实际上表现得像内联(就换行而言),则可以将float: left应用于该元素的CSS。

编辑: 我这样做的方法是在第一个SVG上添加一个名为float-left的类,然后修改您的<style>标签之一以包含

.float-left {
    float: left;
}

这也将允许您将float-left类添加到要执行此行为的任何其他元素上。希望对您有所帮助。

答案 1 :(得分:0)

使用plnkr上的代码,只需将元素的宽度设置为足够小的值,就可以使它们并排放置。为两个元素定义不同的宽度没有帮助(折线图使用分配给HTML元素的namespace Ui { class FooBar; },而箱形图仅将其宽度设置为460)。但是,如果将每个参数设置为一个较小的特定值(最初为200),则会看到它们彼此并排显示很好。

width

此外,由于某种原因,您正在使用完全不同的HTML渲染两个svg元素(一个位于<svg width="200" height="700"> . . . <!-- BOXPLOT --> . . . var margin = {top: 70, right: 30, bottom: 50, left: 100}, width = 200 - margin.left - margin.right, 元素中,另一个位于svg中,带有span),这将无济于事。使您的HTML保持一致,并且您将对其呈现方式有更多的控制权,因为默认情况下,块将以相同的方式处理。