我必须显示一个图表,该图表表示从数据库中提取的点和一条预设的直线。我必须查看这些点相对于这条直线的位置
我开始写程序,以创建2个图表的作品,但我不能显示他们在一起,我知道这是因为散点图使用线性轴的X轴默认和折线图使用类别轴,这些是不兼容的,但我不能使用第二个X轴。
<!DOCTYPE html>
<html>
<head>
<title>Line and Scatter Charts</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div style="width: 50%;">
<canvas id="lineChart"></canvas>
</div>
<div style="width: 50%;">
<canvas id="scatterChart"></canvas>
</div>
<script>
// Define the data for the line chart
var lineData = {
labels: ['Point 1', 'Point 2'],
datasets: [{
label: 'Line Chart',
data: [
{x: 0, y: 0},
{x: 5, y: 10}
],
fill: false,
borderColor: 'rgb(75, 192, 192)',
lineTension: 0.1
}]
};
// Define the options for the line chart
var lineOptions = {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
};
// Create a new line chart
var lineChart = new Chart(document.getElementById('lineChart'), {
type: 'line',
data: lineData,
options: lineOptions
});
// Retrieve data from SQL database
var sqlData = <?php
$servername = "???";
$username = "???";
$password = "???";
$dbname = "???";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve data from database
$sql = "SELECT x,y FROM test";
$result = $conn->query($sql);
// Create array of data for scatter chart
$dispersioneData = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$dispersioneData[] = array(
'x' => $row["x"],
'y' => $row["y"]
);
}
}
echo json_encode($dispersioneData);
// Close connection
$conn->close();
?>;
// Define the data for the scatter chart
var scatterData = {
datasets: [{
label: 'Scatter Chart',
data: sqlData,
backgroundColor: 'rgba(75, 192, 192, 0.5)'
}]
};
// Define the options for the scatter chart
var scatterOptions = {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
};
// Create a new scatter chart
var scatterChart = new Chart(document.getElementById('scatterChart'), {
type: 'scatter',
data: scatterData,
options: scatterOptions
});
</script>
</body>
</html>
1条答案
按热度按时间41ik7eoe1#
您可以创建一个mixed chart,这很自然,唯一不同的是为每个数据集单独设置
type
(图表本身不设置类型);你的线数据与散点数据兼容,因为它已经有了x
和y
。在下面的代码片段中,我用随机散点数据替换了你的sql代码,x在区间[0,6],y在区间[0,10]。