Я пытаюсь создать древовидную карту, которая показывает порядки, семейства, роды и т. д. и т. п. Древовидная карта работает отлично, я использовал пакет 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
Имитация щелчка мыши в древовидной карте HTML, созданной из Python Plotly ⇐ Python
Программы на Python
1734440919
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.`);
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79287995/simulating-mouse-clicking-in-html-treemap-generated-from-python-ploty[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия