JSFiddle - React, Tailwind, and code Playground
by madobon
HTML
<!-- <div class="bar"></div> -->
<svg>
<rect x="0" y="0" width="30" height="30" fill="purple"/>
<rect x="20" y="5" width="30" height="30" fill="blue"/>
<rect x="40" y="10" width="30" height="30" fill="green"/>
<rect x="60" y="15" width="30" height="30" fill="yellow"/>
<rect x="80" y="20" width="30" height="30" fill="red"/>
</svg>
<svg>
<rect x="0" y="0" width="500" height="50"/>
<!-- 長方形 -->
</svg>
<svg>
<circle cx="250" cy="30" r="25" fill="red" stroke="blue" stroke-width="5"/>
<!-- 円 -->
</svg>
<svg>
<ellipse cx="250" cy="25" rx="50" ry="25" />
<!-- 楕円 -->
</svg>
<svg>
<line x1="0" y1="0" x2="500" y2="50" stroke="black" />
<!-- 線 -->
</svg>
<svg>
<text x="100" y="50" font-family="sans-serif" font-size="25" fill="gray">javascript</text>
<!-- テキスト -->
</svg>
<svg>
<circle cx="25" cy="25" r="20" fill="rgba(128, 0, 128, 1.0)"/>
<circle cx="50" cy="25" r="20" fill="rgba(0, 0, 255, 0.75)"/>
<circle cx="75" cy="25" r="20" fill="rgba(0, 255, 0, 0.5)"/>
<circle cx="100" cy="25" r="20" fill="rgba(255, 255, 0, 0.25)"/>
<circle cx="125" cy="25" r="20" fill="rgba(255, 0, 0, 0.1)"/>
</svg>
<div id="kamata"></div>
<ul>
<li>d3.select("body") ? DOM の中から body を見つけ、その参照をチェインの次のステップに渡します。</li>
<li>.selectAll("p") ? DOM 要素のすべてのパラグラフ要素を選択します。ここでは該当する要素が存在しないため、メソッドは空のセレクションを返します。この空のセレクションは、すぐ後に作られるパラグラフ要素を表したものだと理解してください。</li>
<li>enter() は新規にプレースホルダ(※)要素を生成し、そのプレースホルダへの参照をチェインの次のステップに渡します。</li>
<li>data()メソッドを呼ぶことで、その後にチェインされたメソッドの中で、d を入力値として受け取れる無名関数が使えるようになるのです。</li>
<li>attr() は、要素の HTML 属性とその値を設定するために用います。</li>
<li>classed() メソッドを使うと、(複数の)要素に簡単にクラスを追加したり削除することができます。</li>
</ul>
CSS
div.bar {
display: inline-block;
width: 30px;
height: 75px;
/* この数値は実行時に上書きされます */
background-color: teal;
margin-right: 2px;
}
li {
padding: 10px;
}
JavaScript
// 幅( Width )と高さ( height )
var w = 500;
var h = 100;
var barPadding = 1;
var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
// SVG 要素の生成
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
// グラフ
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return h - (d * 4);
})
.attr("width", w / dataset.length - barPadding)
.attr("height", function(d) {
return d * 4;
})
.attr("fill", function(d) {
return "rgb(0, 0, " + (d * 10) + ")";
});
// 文字
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return i * (w / dataset.length) + (w / dataset.length - barPadding) / 2;
})
.attr("y", function(d) {
return h - (d * 4) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");