Echarts中legend图例的rich属性实现自定义图例的样式-饼图-柱状图等

文章介绍了如何使用ECharts库来定制图表的样式,包括legend、axisLabel和title的formatter,以及在Vue组件中处理饼图数据和响应式事件,如鼠标悬浮和图例交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 上图表,展示的字体颜色是不同的,而且和名称之间是有间距

使用rich实现

const options = {
    textStyle: {
        rich: {
           orgname: {
             fontSize: 12,
             width: 100,
           },
         count: {
              fontSize: 12
              verticalAlign: 'top',
              align: 'center',
              color: '#597FF3',
              padding: [0, 0, 0, 15],
             },
        },
    },
    legend: {
        formatter:(name) => {
            let target;
            const data = this.fmsDevice;
            for (let i = 0; i < data.length; i++) {
               if (data[i].orgname === name) {
                   target = `${data[i].count}辆`;
               }
           }
           const arr = [
               `{orgname|${name}}`,
               `{count|${target}}`,
            ];
           return arr.join('');
        }
    }
 }

在formatter自定义样式名称,在textStyle中定义样式内容。当然我们在自定义title样式时也可以使用同样的方法

使用rich设置axisLabel

 设置axisLabel的样式。可以在axisLabel中设置formtter,添加自定义样式名称

xAxis: [
    {
       axisLabel: {
          color: '#747DA0',
          fontSize: 12,
          formatter: name => (`{name|${name}}`),
          rich: {
             name: {
                color: '#fff',
                shadowBlur: 3,
                borderWidth: 1,
                borderColor: 'green',
                borderRadius: 2,
             },
          },
       },
    }
]

调整图例的样式 icon属性 

legend: {
      data: [`${name}价格`, 'Binance', 'OKX', 'Bitget'],
      inactiveColor: '#ccc',

      icon: 'rect',
      itemGap: 13,
      itemHeight: 10,
      itemWidth: 10,
      selectedMode: false,
      type: 'scroll',

      textStyle: {
        color: '#fff'
      }
    },

 ---->  

饼图数据展示

悬浮改变显示内容 

<LockPieChart class="pie-chart" :data="data" />

const LineData3 = ref([
  { value: 20, name: 'OKX1', sy: 666 },
  { value: 60, name: 'OKX2', sy: 333 },
  { value: 40, name: 'OKX3', sy: 222 }
]);
<!--
 * @Author: Jackie
 * @Date: 2023-07-07 10:38:02
 * @LastEditTime: 2023-07-27 14:28:39
 * @LastEditors: Jackie
 * @Description: 饼图
 * @FilePath: /components/TracChart/PieChart/LockPieChart.vue
 * @version: 
-->
<template>
  <div class="pie-chart" ref="myEcharts"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineProps, watch } from 'vue';
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  }
});
onMounted(() => {
  console.log(props.data);
  initChart(props.data);
});
watch(
  () => props.data,
  (val) => {
    initChart(props.data);
  },
  { deep: true, immediate: false }
);

onUnmounted(() => {
  myChart.dispose();
  window.removeEventListener('resize', myChart.resize);
});

//隐藏title
const hideTitle = (e) => {
  myChart.setOption({
    title: {
      text: '',
      subtext: ''
    }
  });
};
//显示title
const showTitle = (e) => {
  myChart.setOption({
    title: {
      text:
        '$' +
        props.data.reduce((sum, item, index, array) => {
          return sum + item.value;
        }, 0),
      subtext: '总数量'
    }
  });
};

let myChart = '';
const myEcharts = ref(null);

const initChart = (data) => {
  window.echarts.init(myEcharts.value).dispose();
  myChart = window.echarts.init(myEcharts.value);

  // 给饼图添加事件
  // 当区域高亮时隐藏title,比如当鼠标移动到legend上时
  myChart.on('highlight', hideTitle);
  // 当鼠标悬浮到区域时隐藏title
  myChart.on('mouseover', hideTitle);
  // 当鼠标离开区域时显示title
  myChart.on('mouseout', showTitle);
  // 当区域取消高亮时显示title,比如当鼠标从legend上离开时
  myChart.on('downplay', showTitle);

  // 设置option
  const option = {
    title: {
      text:
        '$' +
        data.reduce((sum, item, index, array) => {
          return sum + item.value;
        }, 0),
      subtext: '总数量',
      x: '34.3%',
      y: '42.3%',
      textAlign: 'center',
      textStyle: {
        color: '#000',
        fontSize: '36px',
        fontWeight: 'bold',
        lineHeight: 30,
        fontFamily: 'DIN',
        fontWight: '500'
      },
      subtextStyle: {
        color: '#868E9B',
        fontSize: '16px',
        fontWeight: 'bold',
        fontFamily: 'PingFang SC',
        fontWeight: '500'
      }
    },
    // tooltip: {
    //   trigger: 'item',
    //   formatter: '{b}: {d}%-{c}'
    // },
    legend: {
      // type: "scroll",
      show: true,
      // top: "28%",
      y: 'center',
      left: 'right',
      icon: 'circle',
      // selectedMode: false, // 控制是否可以通过点击图例改变系列的显示状态 --
      orient: 'vertical', // 布局方式,默认为水平布局,可选为:'horizontal' ¦ 'vertical'
      padding: [0, 20, 0, 10],
      align: 'left', //图例文字在右边
      itemGap: 20, // 图例间隙
      textStyle: {
        //图例文字的样式
        fontFamily: 'DIN',
        fontWeight: '700',
        color: '#000',
        fontSize: '16px',
        backgroundColor: 'transparent',
        rich: {
          orgname: {
            fontSize: '16px',
            width: 70,
            color: '#000',
            fontFamily: 'DIN',
            fontWeight: '700'
          },
          count: {
            fontSize: '16px',
            verticalAlign: 'top',
            align: 'center',
            color: '#000',
            padding: [0, 0, 0, 15],
            fontFamily: 'DIN',
            fontWeight: '500'
          }
        }
        // lineHeight: 14,
        // padding: [0, 0, 0, 20],
      },
      data: data.map((item) => item.name), //图例组件
      formatter: (name) => {
        let num = '';

        data.forEach((item) => {
          //格式化图例文本,支持字符串模板和回调函数两种形式。
          if (item.name === name) {
            num = String(item.value).replace(/(\d)(?=(?:\d{6})+$)/g, '$1.');
            return;
          }
        });

        let total = data.reduce((sum, item, index, array) => {
          return sum + item.value;
        }, 0);
        let p = Math.round((num / total) * 10000) / 100;
        return `{orgname|${name}}{count|${p}%}`;
      }
    },
    series: [
      {
        name: '分类统计',
        type: 'pie',
        radius: ['60%', '80%'],
        center: ['35%', '50%'], //偏移
        avoidLabelOverlap: false,
        // itemStyle: {
        //   borderRadius: 10,
        //   borderColor: '#fff',
        //   borderWidth: 2
        // },
        label: {
          show: false,
          position: 'center'
        },
        // 鼠标悬浮时中心位置显示对应区域的信息
        emphasis: {
          label: {
            show: true,
            formatter: '{num|${c}}\n{title|{b}}',
            fontSize: '26px',
            fontWeight: 'bold',
            // color: () => {},
            lineHeight: 30,
            rich: {
              num: {
                color: '#000',
                fontFamily: 'DIN',
                fontSize: '36px',
                fontWeight: '500',
                padding: [0, 0, 0, 0]
              },
              title: {
                // color: '#868E9B',
                // fontFamily: 'PingFang SC',
                fontSize: '20px',
                fontWeight: '500',
                padding: [20, 0, 0, 0]
              }
            }
          }
        },
        //emphasis: false, // --
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  };
  option && myChart.setOption(option);
  window.addEventListener('resize', myChart.resize);
};
</script>

<style lang="less" scoped>
.pie-chart {
  width: 100%;
  height: 100%;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JackieDYH

谢谢您嘞!我会继续加油地

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值