Имитация щелчка мыши в древовидной карте HTML, созданной из Python PlotlyPython

Программы на Python
Ответить
Anonymous
 Имитация щелчка мыши в древовидной карте HTML, созданной из Python Plotly

Сообщение Anonymous »

Я пытаюсь создать древовидную карту, которая показывает порядки, семейства, роды и т. д. и т. п. Древовидная карта работает отлично, я использовал пакет Ploty из Python, импортированные данные находятся в файле csv, а полученная древовидная карта сохраняется как html. Поскольку у меня более 1200 видов, я хочу добавить функцию поиска, реализовав javascript, который позволяет мне вставлять определенный ранг (например, название семейства) и автоматически перемещаться по древовидной карте. Функция поиска совпадений работает, а навигация нет.
Будем очень благодарны за любую помощь.

function searchSquare() {
// Get the search query; If I remove the toLowerCase it stops working
const query = document.getElementById('searchInput').value.toLowerCase();
const treemapDiv = document.querySelector('.plotly-graph-div'); // Find the Plotly graph div

if (!treemapDiv) {
alert("Treemap container not found!");
return;
}

// Access the plot data via Plotly's internal structure
const plotData = treemapDiv.data || [];

if (plotData.length === 0) {
alert("No data found in the treemap!");
return;
}

const trace = plotData[0]; // Assuming the first trace contains the treemap data
const labels = trace.labels || []; // All labels in the treemap

if (!labels || labels.length === 0) {
alert("No labels found in the treemap data!");
return;
}

// Search for the query in all labels
const matchFound = labels.some(label => label.toLowerCase().includes(query)); // Check if query is present

if (matchFound) {
alert(`"${query}" is present in the treemap!`);
const matchIndex = labels.findIndex(label => label.toLowerCase().includes(query));
// Found a match
const matchLabel = labels[matchIndex];
console.log(`Found match: ${matchLabel} at index ${matchIndex}`);

// Retrieve calcdata to get pixel coordinates
const calcData = treemapDiv._fullData[0]._coord; // Access the computed layout
const nodeCoordinates = calcData[matchIndex]; // Get coordinates for the matched node

if (nodeCoordinates) {
const [xMin, yMin, xMax, yMax] = nodeCoordinates; // Bounding box
const xCenter = (xMin + xMax) / 2; // Center x-coordinate
const yCenter = (yMin + yMax) / 2; // Center y-coordinate

console.log(`Pixel coordinates: (${xCenter}, ${yCenter})`);

// Simulate a click event at the pixel coordinates
const clickEvent = new MouseEvent('click', {
bubbles: true,
cancelable: true,
clientX: xCenter,
clientY: yCenter
});

treemapDiv.dispatchEvent(clickEvent);

alert(`Navigated to: ${matchLabel}`);
} else {
alert(`"${query}" is NOT present in the treemap.`);
}
}




Подробнее здесь: https://stackoverflow.com/questions/792 ... thon-ploty
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»