Is it possible to show a message text on the chart

2019-08-16 14:04发布

问题:

I'm working with Biilboard.js, a library which is based on D3.

I created a chart and I want to be able to show a message on it, for example if Y-axis is greater than 100 or anything like this, doesn't matter the condition.

This is an example of what I want which is done with pure D3 (I guess):

Basically, if that condition is fulfilled, that message box appears over the chart.

Do you have any ideas of to do this?

回答1:

There're several ways to do that.

  • 1) Add y Axis grid text
  • 2) Simply, add some normal DOM element(ex. div, etc.) and handle it to be positioned over chart element

I'll try put some example using the first one and check for the ygrids() API doc.

// variable to hold min and max value
var min;
var max;

var chart = bb.generate({
	data: {
		columns: [
			["sample", 30, 200, 100, 400, 150, 250]
		],
		onmin: function(data) {
			min = data[0].value;
		},
		onmax: function(data) {
			max = data[0].value;
		}
	}
});

// add y grids with deterimined css classes to style texts added
chart.ygrids([
	{value: min, text: "Value is smaller than Y max", position: "start", class: "min"},
	{value: max, text: "Value is greater than Y max", position: "start", class: "max"}
]);
/* to hide grid line */
.min line, .max line{
    display:none;
}

/* text styling */
.min text, .max text{
    font-size:20px;
    transform: translateX(10px);
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.pkgd.min.js"></script>
    <title>billboard.js</title>
</head>

<body>
  <div id="chart"></div>
</body>
</html>