我正在为 Flask Web 应用程序编写此代码,其中提供的数据将从 Flask 函数获取响应作为 json 数据,并使用plotlyjs 在 Web 应用程序中显示气泡图
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="bubble-chart" style="width: 800px; height: 400px;"></div>
<script>
var xdat = [900, 920, 940, 960, 980, 1000, 1020, 1040, 1060, 1080, 1100];
var ydat = [3, 10, 102, 369, 241, 476, 47, 53, 20, 13, 67];
var sizdat = [16150, 29750, 79050, 79900, 98600, 193800, 23800, 45900, 18700, 8500, 76500];
// Scale the marker sizes based on sizdat
var sizdatScaled = sizdat.map(function(value) {
return Math.sqrt(value); // Scaled based on the square root for visibility
});
// Define the maximum and minimum marker sizes
var maxMarkerSize = 40; // Adjust as needed
var minMarkerSize = 4; // Adjust as needed
// Normalize the scaled sizdat values to fit within the marker size limits
var sizdatNormalized = sizdatScaled.map(function(value) {
return minMarkerSize + (maxMarkerSize - minMarkerSize) * (value - Math.min(...sizdatScaled)) / (Math.max(...sizdatScaled) - Math.min(...sizdatScaled));
});
// Create hover text based on sizdat
var hoverText = sizdat.map(function(value) {
return 'SizDat: ' + value; // Customize the hover text as needed
});
// Create the trace for the bubble chart
var trace = {
x: xdat,
y: ydat,
mode: 'markers',
marker: {
size: sizdatNormalized,
sizemode: 'diameter',
color: 'blue',
opacity: 0.5,
line: {
width: 1,
},
hoverinfo: 'text',
text: hoverText, // Use the hover text here
},
hovertemplate: "<b>X: %{x}</b><br>" +
"<b>Y: %{y}</b><br>" +
"<b>Size: %{marker.size}</b><br>" + // Include %{marker.size} for displaying size values
"<extra></extra>"
};
var data = [trace];
// Create the bubble chart
var layout = {
title: 'Bubble Chart with Scaled Marker Sizes',
xaxis: {
title: 'X-axis Label',
},
yaxis: {
title: 'Y-axis Label',
},
};
Plotly.newPlot('bubble-chart', data, layout);
</script>
</body>
</html>
此图表显示正确。这里 sizdat[] 是第三个维度,具有很小和非常大的值,因此为了根据图表大小进行拟合,它被标准化,图表显示 xdata、ydata 和 sizdat 标准化值的悬停文本。但我需要 xdat、ydat和要在气泡上悬停时显示的 sizdat 值,即,而不是 sizdatNormalizd 数据,它应该显示原始值的 sizdat 数据,该原始值位于以 sizdat[] 开头给出的标准化值之前
在现有代码中,您已经生成了hoverText数组,其中包含悬停文本形式的原始sizdat值。您可以自定义悬停模板以包含此数组中的文本。
var trace = {
x: xdat,
y: ydat,
mode: 'markers',
marker: {
size: sizdatNormalized,
sizemode: 'diameter',
color: 'blue',
opacity: 0.5,
line: {
width: 1,
},
hoverinfo: 'text',
text: hoverText, // Use the hover text here
},
hovertemplate: "<b>X: %{x}</b><br>" +
"<b>Y: %{y}</b><br>" +
"<b>Size: %{text}</b><br>" + // Use %{text} to display hoverText (original sizdat values)
"<extra></extra>"
};
现在将鼠标悬停在每个气泡上将显示原始 sizdat 值以及 xdat 和 ydat 值。