一、legend 概述
echarts 的 legend 組件用於展示數據系列的信息,常用於多系列展示的圖表中。通過 legend,用戶可以方便地選擇需要呈現的數據系列。
在 echarts 中,legend 可以設置其位置、方向、顯示內容等屬性,並且支持對單一系列的 legend 進行個性化設置,也支持通過點擊 legend 上的某一項來隱藏或顯示對應的數據系列。
二、legend 的基本屬性
在 echarts 中,我們可以通過 option 對象的 legend 屬性來配置 legend 的基本屬性。下面是一個示例:
option = { legend: { data: ['數據系列1', '數據系列2', '數據系列3'], orient: 'horizontal', left: 'center', }, series: [ { name: '數據系列1', type: 'line', data: [10, 20, 30, 40, 50], }, { name: '數據系列2', type: 'line', data: [20, 40, 60, 80, 100], }, { name: '數據系列3', type: 'line', data: [5, 15, 25, 35, 45], }, ], }
上述代碼中,legend 的基本屬性包括:
1. data:一個包含 legend 數據的數組,即每個數據系列的名稱。
2. orient:legend 的排布方向,支持 horizontal(水平)和 vertical(垂直)。
3. left/top/right/bottom:legend 相對於畫布的左/上/右/下距離。
三、單一系列的 legend 個性化設置
有時候,我們需要針對某個數據系列設置特定的 legend 樣式。對於單一系列的個性化設置,echarts 提供了 itemStyle 屬性來實現。下面是一個示例:
option = { legend: { data: ['數據系列1', '數據系列2', '數據系列3'], }, series: [ { name: '數據系列1', type: 'line', data: [10, 20, 30, 40, 50], itemStyle: { color: 'red', }, }, { name: '數據系列2', type: 'line', data: [20, 40, 60, 80, 100], }, { name: '數據系列3', type: 'line', data: [5, 15, 25, 35, 45], }, ], }
上述代碼中,我們針對數據系列1設置了 itemStyle: {color: 'red'}
,表示在 legend 中,數據系列1 的樣式為紅色。
四、點擊 legend 實現數據系列的隱藏和顯示
除了展示數據系列的信息外,legend 還可以用於控制數據系列的隱藏和顯示。我們可以通過設置 series 類型為 'line'
或 'bar'
等可進行隱藏和顯示的類型,然後設置 legend 的 selectedMode: 'single'
或 selectedMode: 'multiple'
來切換對應的隱藏和顯示模式。例如:
option = { legend: { data: ['數據系列1', '數據系列2', '數據系列3'], selectedMode: 'multiple', }, series: [ { name: '數據系列1', type: 'line', data: [10, 20, 30, 40, 50], }, { name: '數據系列2', type: 'line', data: [20, 40, 60, 80, 100], }, { name: '數據系列3', type: 'line', data: [5, 15, 25, 35, 45], // 設置為false表示默認不顯示該數據系列 // 但是點擊legend可以進行顯示與隱藏 show: false, }, ], }
上述代碼中,我們針對數據系列3設置了 show: false
,表示該數據系列默認不顯示。通過設置 selectedMode 為 multiple,用戶可以在 legend 中勾選多個數據系列進行同時顯示,與單擊某一系列的 legend 來顯示該系列的方法類似。
五、legend 的高級屬性
除了上述基本屬性外,echarts 的 legend 還有一些高級屬性可用於進一步控制其樣式和行為。下面是一些常見的高級屬性:
textStyle
:legend 的字體樣式formatter
:legend 的文本內容格式化器selected
:設置每個數據系列的顯示狀態,可用於默認隱藏某些系列inactiveColor
:設置未被選中的數據系列的字體顏色padding
:設置 legend 內容的內邊距itemGap
:設置 legend 中每個數據系列之間的間距
我們可以在 option 對象的 legend 屬性中自定義這些高級屬性。例如:
option = { legend: { data: ['數據系列1', '數據系列2', '數據系列3'], textStyle: { fontSize: 14, fontWeight: 'bold', color: '#333', }, formatter: '{name}', padding: [10, 0], itemGap: 20, }, series: [ { name: '數據系列1', type: 'line', data: [10, 20, 30, 40, 50], }, { name: '數據系列2', type: 'line', data: [20, 40, 60, 80, 100], }, { name: '數據系列3', type: 'line', data: [5, 15, 25, 35, 45], // 默認隱藏該數據系列 show: false, // 未被選中時字體的顏色 inactiveColor: 'gray', }, ], }
上述代碼中,我們自定義了 textStyle、formatter、padding、itemGap 和 inactiveColor 等 legend 屬性。
六、總結
本文深入解析了 echarts 的 legend 組件,從基本屬性、單一系列的個性化設置、點擊 legend 實現數據系列的隱藏和顯示以及高級屬性等多個方面進行了詳細闡述。希望本文可以幫助讀者更好地理解和使用 echarts 的 legend 組件。
原創文章,作者:RHUGE,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/313738.html