我正在尝试向酒窝条形图中的每个条形添加数据标签。我想添加与此示例中显示的相同内容。http://dimplejs.org/advanced_examples_viewer.html?id=advanced_custom_styling。但是我想在图表中的每个条形图上添加数字。我的代码如下。我不知道如何捕捉'rect'形状并在其上附加文字。请告知。
<div id="test" class="column">
<script type="text/javascript">
var svg = dimple.newSvg("#test", 590, 335);
var data = [
{"Month": "2014-01-10", "Color": "Yellow", "Percentage": 20},
{"Month": "2014-02-10", "Color": "Yellow", "Percentage": 32},
{"Month": "2014-03-10", "Color": "Yellow", "Percentage": 20},
{"Month": "2014-04-10", "Color": "Yellow", "Percentage": 32},
{"Month": "2014-01-10", "Color": "Red", "Percentage": 10},
{"Month": "2014-02-10", "Color": "Red", "Percentage": 25},
{"Month": "2014-03-10", "Color": "Red", "Percentage": 15},
{"Month": "2014-04-10", "Color": "Red", "Percentage": 30}
];
var chart = new dimple.chart(svg, data);
chart.setBounds(80, 30, 340, 200);
var x = chart.addCategoryAxis("x", ["Month", "Color"]);
var y1 = chart.addMeasureAxis("y", "Percentage");
var bars = chart.addSeries("Color", dimple.plot.bar, [x, y1]);
bars.barGap = 0.5;
chart.addLegend(50, 10, 510, 20, "right");
chart.draw();
svg.append("text")
.attr("x", chart._xPixels() + chart._widthPixels() / 2)
.attr("y", chart._yPixels() - 10)
.style("text-anchor", "middle")
.style("font-family", "sans-serif")
.style("font-size", "75%")
.text("Sample Text")
</script>
答案 0 :(得分:1)
链接示例中与条形标签相关的部分是这一部分:
// Set some custom display elements for each series shape
mySeries.afterDraw = function (s, d) {
var shape = d3.select(s);
// Add some bar labels for the yValue
svg.append("text")
.attr("x", parseFloat(shape.attr("x")) + shape.attr("width") / 2)
.attr("y", parseFloat(shape.attr("y")) + (shape.attr("height") > 30 ? (shape.attr("height") / 2 + 8) : - 10))
.style("font-family", "courier new")
.style("text-anchor", "middle")
.style("font-size", "16px")
.style("fill", "#ecf0f1")
.style("pointer-events", "none")
.text(yAxis._getFormat()(d.yValue));
};
这有一个检查,如果矩形的高度小于30,则将文本放在顶部。因此,您只需要修改y赋值以删除条件:
.attr("y", parseFloat(shape.attr("y")) - 10)
这应该将所有标签放在条形图的顶部。
答案 1 :(得分:0)
svg.append("text")
.attr("x", chart._xPixels() + chart._widthPixels() / 2)
.attr("y", chart._yPixels() - 10)
.style("text-anchor", "middle")
.style("font-family", "sans-serif")
.style("font-size", "75%")
.text("Sample Text")
在上面的代码中,.attr("x", chart._xPixels() + chart._widthPixels() / 2)
是将文本保持为水平,.attr("y", chart._yPixels() - 10)
是保持文本垂直,因此如果您需要将文本保留在rect的顶部,请使用您正在使用的y属性对于rect并添加一些数字以便在rect上保留文本。
希望你能理解。如果没有要求更多。好的