阿里云主机折上折
  • 微信号
Current Site:Index > Tree Chart

Tree Chart

Author:Chuan Chen 阅读数:63840人阅读 分类: ECharts

Tree Chart Implementation

A tree chart is a type of visualization used to display hierarchical data, particularly suited for showcasing parent-child relationships or organizational structures. ECharts provides robust support for tree charts, enabling the display of complex tree structures with simple configurations.

Basic Tree Chart Configuration

To implement a tree chart in ECharts, hierarchical data must be prepared, and the series.type must be specified as 'tree'. Below is a basic example of a tree chart configuration:

option = {
    series: [{
        type: 'tree',
        data: [{
            name: 'Root Node',
            children: [{
                name: 'Child Node 1',
                children: [
                    { name: 'Child Node 1.1' },
                    { name: 'Child Node 1.2' }
                ]
            }, {
                name: 'Child Node 2',
                children: [
                    { name: 'Child Node 2.1' },
                    { name: 'Child Node 2.2' }
                ]
            }]
        }],
        symbol: 'circle',
        symbolSize: 7,
        orient: 'vertical',
        label: {
            position: 'top',
            verticalAlign: 'middle',
            align: 'center'
        },
        leaves: {
            label: {
                position: 'right',
                verticalAlign: 'middle',
                align: 'left'
            }
        }
    }]
};

Data Format Requirements

Tree chart data must adhere to a specific nested structure. Each node can include the following properties:

  • name: The display name of the node
  • value: The numerical value of the node (optional)
  • children: An array of child nodes (optional)
  • itemStyle: Node styling (optional)
  • label: Label styling (optional)
// Example of complex data
const treeData = {
    name: 'Company Structure',
    value: 100,
    itemStyle: {
        color: '#5470c6'
    },
    children: [
        {
            name: 'Technology Department',
            value: 40,
            children: [
                { name: 'Frontend Team', value: 15 },
                { name: 'Backend Team', value: 20 },
                { name: 'Testing Team', value: 5 }
            ]
        },
        {
            name: 'Marketing Department',
            value: 30,
            children: [
                { name: 'Promotion Team', value: 10 },
                { name: 'Sales Team', value: 20 }
            ]
        }
    ]
};

Layout Direction Control

ECharts tree charts support multiple layout directions, controlled by the orient property:

// Horizontal layout
orient: 'horizontal'

// Vertical layout (default)
orient: 'vertical'

// Radial layout
orient: 'radial'

Example of radial layout:

option = {
    series: [{
        type: 'tree',
        data: [treeData],
        orient: 'radial',
        symbol: 'emptyCircle',
        symbolSize: 7,
        expandAndCollapse: true,
        initialTreeDepth: 3,
        label: {
            rotate: 0,
            position: 'left'
        },
        leaves: {
            label: {
                position: 'right'
            }
        }
    }]
};

Interactive Features

ECharts tree charts support rich interactive features, including node expansion/collapse, zooming, and panning:

option = {
    series: [{
        type: 'tree',
        data: [treeData],
        roam: true,  // Enable zooming and panning
        expandAndCollapse: true,  // Allow expansion and collapse
        initialTreeDepth: 2,  // Initial expansion depth
        itemStyle: {
            borderColor: '#999'
        },
        emphasis: {  // Highlight styling
            focus: 'ancestor',
            itemStyle: {
                borderColor: '#333'
            }
        }
    }],
    tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}'
    }
};

Custom Styling

Tree charts can be styled in various ways:

option = {
    series: [{
        type: 'tree',
        data: [treeData],
        lineStyle: {
            color: '#ccc',
            width: 2,
            curveness: 0.5  // Connector line curvature
        },
        itemStyle: {
            color: function(params) {
                // Set different colors based on depth
                const depth = params.data.depth;
                const colorList = ['#c23531','#2f4554','#61a0a8','#d48265'];
                return colorList[depth % colorList.length];
            },
            borderWidth: 1
        },
        label: {
            fontSize: 12,
            color: '#333',
            formatter: function(params) {
                // Customize label display
                return `${params.name} (${params.value || 0})`;
            }
        }
    }]
};

Advanced Features: Animation Effects

ECharts tree charts support rich animation effects:

option = {
    series: [{
        type: 'tree',
        data: [treeData],
        animationDuration: 800,
        animationDurationUpdate: 500,
        animationEasing: 'elasticOut',
        expandAndCollapse: true,
        symbol: 'path://M10,10 L50,10 L50,50 L10,50 Z',  // Custom node shape
        symbolSize: [20, 20],
        itemStyle: {
            opacity: 0.8,
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
        }
    }]
};

Large Data Optimization

For large tree structures, performance optimization is necessary:

option = {
    series: [{
        type: 'tree',
        data: [largeTreeData],
        layout: 'orthogonal',  // Orthogonal layout for better performance
        symbolSize: 6,
        label: {
            show: false  // Disable labels to improve performance
        },
        leaves: {
            label: {
                show: true  // Only show leaf node labels
            }
        },
        emphasis: {
            disabled: true  // Disable highlight effects
        },
        animation: false  // Disable animations
    }]
};

Combining with Other Chart Types

Tree charts can be combined with other chart types:

option = {
    tooltip: {
        trigger: 'item',
        triggerOn: 'mousemove'
    },
    series: [
        {
            type: 'tree',
            data: [treeData],
            top: '5%',
            left: '7%',
            bottom: '5%',
            right: '60%',
            symbolSize: 10,
            label: {
                position: 'left',
                verticalAlign: 'middle',
                align: 'right'
            },
            leaves: {
                label: {
                    position: 'right',
                    verticalAlign: 'middle',
                    align: 'left'
                }
            }
        },
        {
            type: 'pie',
            radius: ['15%', '30%'],
            center: ['75%', '50%'],
            data: pieData,
            label: {
                position: 'inner'
            }
        }
    ]
};

Dynamic Data Updates

Tree charts support dynamic data updates:

// Initialize the chart
const myChart = echarts.init(document.getElementById('main'));
myChart.setOption(option);

// Dynamically update data
function updateTreeData(newData) {
    myChart.setOption({
        series: [{
            type: 'tree',
            data: [newData]
        }]
    });
}

// Example: Expand all nodes
function expandAll() {
    const option = myChart.getOption();
    option.series[0].initialTreeDepth = Infinity;
    myChart.setOption(option);
}

Event Handling

Various interactive events can be added to tree charts:

myChart.on('click', function(params) {
    console.log('Clicked node:', params.name);
    if (params.data.children) {
        // Handle logic for nodes with children
    }
});

myChart.on('dblclick', function(params) {
    console.log('Double-clicked node:', params.name);
});

myChart.on('mouseover', function(params) {
    // Handle mouse hover
});

myChart.on('globalout', function() {
    // Handle mouse exit
});

Responsive Design

Implement responsive layouts for tree charts:

function resizeChart() {
    myChart.resize();
}

window.addEventListener('resize', resizeChart);

// Example of responsive configuration
option = {
    series: [{
        type: 'tree',
        data: [treeData],
        layout: function() {
            // Determine layout direction based on window width
            return window.innerWidth < 768 ? 'vertical' : 'horizontal';
        }(),
        label: {
            fontSize: function() {
                return window.innerWidth < 768 ? 10 : 12;
            }()
        }
    }]
};

Exporting and Printing

Implement export functionality for tree charts:

// Export as image
document.getElementById('export-btn').addEventListener('click', function() {
    const imgData = myChart.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
    });
    const link = document.createElement('a');
    link.href = imgData;
    link.download = 'tree-chart.png';
    link.click();
});

// Print the chart
document.getElementById('print-btn').addEventListener('click', function() {
    const printWindow = window.open('', '_blank');
    printWindow.document.write('<html><head><title>Tree Chart Print</title></head><body>');
    printWindow.document.write('<img src="' + myChart.getDataURL() + '">');
    printWindow.document.write('</body></html>');
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
});

Theme Customization

Customize tree chart styles with themes:

// Register a theme
echarts.registerTheme('myTheme', {
    color: ['#c12e34', '#e6b600', '#0098d9', '#2b821d'],
    tree: {
        itemStyle: {
            borderColor: '#555'
        },
        lineStyle: {
            color: '#888',
            width: 1
        }
    }
});

// Apply the theme
const myChart = echarts.init(document.getElementById('main'), 'myTheme');

Accessibility

Enhance accessibility for tree charts:

option = {
    series: [{
        type: 'tree',
        data: [treeData],
        aria: {
            enabled: true,
            label: {
                description: 'Tree chart showing company structure, with {depth} levels, current node: {name}'
            }
        },
        label: {
            show: true,
            color: '#333',
            fontSize: 14,
            fontWeight: 'bold'
        },
        itemStyle: {
            color: '#4e79a7',
            borderColor: '#333'
        }
    }]
};

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.