宝塔山 发表于 2024-9-24 01:21:11

Echarts 柱状图实现同时表现百分比+原始值+汇总值

原始结果:柱状图
https://i-blog.csdnimg.cn/blog_migrate/55d7fe886ce05bf5a351146f5386c2a7.png
二开结果1:
https://i-blog.csdnimg.cn/direct/5adbccd1ff0149ad8dcc0a84a45662c5.png
核心逻辑
   同时表现百分比和原始值
 label: {
      show: true,
      position: 'inside',
      formatter: (params) => {
        const rawValue = rawData;
        const percentage = Math.round(params.value * 1000) / 10;
        return `${rawValue} \n(${percentage}%)`;
      }
    },    表现汇总值
// Add a new series for displaying total values
series.push({
    name: 'Total',
    type: 'bar',
    stack: 'total',
    itemStyle: {
      color: 'rgba(0,0,0,0)' // 透明颜色
    },
    label: {
      show: true,
      position: 'top',
      formatter: params => `Total: ${totalData}`
    },
    data: totalData.map(value => 0.01) // 微小的值以便能显示标签但不影响图形
}); 代码表明
   
[*] 新增表现总值的系列:

[*]您添加了一个名为 'Total' 的新系列到 series 数组中。
[*]这个系列使用 type: 'bar',并且堆叠在名为 'total' 的堆栈中,这与其他系列使用的堆栈名称一致。这确保了柱状图的对齐,纵然该系列是不可见的。

[*] 透明的柱状图:

[*]itemStyle 被设置为 color: 'rgba(0,0,0,0)',使得该系列的柱状图完全透明。这是一个巧妙的方法,可以确保这些柱状图不增长任何可见的元素到图表中,但仍然可以在它们上面放置标签。

[*] 标签配置:

[*]label 对象中的 show: true 确保表现标签。
[*]position 设置为 'top',因此标签表现在每个柱状图堆栈的顶部。
[*]formatter 函数自定义了标签的文本。它使用 params.dataIndex 获取 totalData 中对应的值,并表现为 Total: {value}。这提供了关于每个类别(星期几)中所有堆叠元素的总值的清楚信息。

[*] 带有微小值的数据:

[*]该系列的 data 数组被设置为 totalData.map(value => 0.01)。这将每个数据点设置为一个非常小的值(0.01)。这些微小的值的目的是为标签创建一个占位符,而不影响图表的实际可视化。由于柱状图本身是透明的,这个值确保了标签可以正确地定位和表现,而不会为柱状图增长任何视觉重量。

分析:



[*]使用透明的柱状图来表现标签:通过使用透明的柱状图,您可以在柱状图堆栈的顶部放置标签,而不会改变图表的视觉外观。这是一种常见的技术,当您盼望添加额外的信息而不影响数据的可视化时。
[*]数据中的微小值:使用微小值(0.01)确保标签与柱状图相关联,但不会显著地影响堆叠柱状图的高度。这在ECharts中尤其有用,由于标签是与特定的数据点相关联的。
[*]堆叠配置:使用相同的堆叠标识符('total')使透明柱状图与其余堆叠柱状图完美对齐,确保标签位置的一致性。
这种方法对于突出表现总值,同时保持数据可视化的完整性非常有用。这是一个为图表提供额外信息而不使其变得杂乱或扭曲的巧妙解决方案。
完整版代码
// There should not be negative values in rawDataconst rawData = [,,,,];const totalData = [];for (let i = 0; i < rawData.length; ++i) {let sum = 0;for (let j = 0; j < rawData.length; ++j) {    sum += rawData;}totalData.push(sum);}const grid = {left: 100,right: 100,top: 50,bottom: 50};const series = ['Direct','Mail Ad','Affiliate Ad','Video Ad','Search Engine'].map((name, sid) => {return {    name,    type: 'bar',    stack: 'total',    barWidth: '60%',    label: {      show: true,      position: 'inside',      formatter: (params) => {      const rawValue = rawData;      const percentage = Math.round(params.value * 1000) / 10;      return `${rawValue} \n(${percentage}%)`;      }    },    data: rawData.map((d, did) =>      totalData <= 0 ? 0 : d / totalData    )};});// Add a new series for displaying total values
series.push({
    name: 'Total',
    type: 'bar',
    stack: 'total',
    itemStyle: {
      color: 'rgba(0,0,0,0)' // 透明颜色
    },
    label: {
      show: true,
      position: 'top',
      formatter: params => `Total: ${totalData}`
    },
    data: totalData.map(value => 0.01) // 微小的值以便能显示标签但不影响图形
});option = {legend: {    selectedMode: false},grid,yAxis: {    type: 'value'},xAxis: {    type: 'category',    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']},series}; 二开结果2:
https://i-blog.csdnimg.cn/direct/2fe4ce4d56f743cc8661183dedd6d1cd.png
 完整版代码
// There should not be negative values in rawData
const rawData = [
,
,
,
,

];

const totalData = [];
for (let i = 0; i < rawData.length; ++i) {
let sum = 0;
for (let j = 0; j < rawData.length; ++j) {
    sum += rawData;
}
totalData.push(sum);
}

const grid = {
left: 100,
right: 100,
top: 50,
bottom: 50
};

const series = [
'Direct',
'Mail Ad',
'Affiliate Ad',
'Video Ad',
'Search Engine'
].map((name, sid) => {
return {
    name,
    type: 'bar',
    stack: 'total',
    barWidth: '60%',
    label: {
      show: true,
      position: 'inside', // Position the labels on top of the bars
      formatter: (params) => {
      const originalValue = rawData;
      const percentage = (originalValue / totalData * 100).toFixed(2);
      return `${originalValue} \n(${percentage}%)`;
      },
    },
    data: rawData.map((d, did) =>
      totalData <= 0 ? 0 : d / totalData
    )
};
});

option = {
tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: (params) => {
      const total = totalData.dataIndex];
      const header = `<div style="font-weight:bold">${params.axisValue}</div>
                      <div>Total: ${total}</div>`;
      const body = params.map(param => {
      const originalValue = rawData;
      const percentage = (originalValue / total * 100).toFixed(2);
      return `<div>${param.seriesName}: ${originalValue} (${percentage}%)</div>`;
      }).join('');
      return header + body;
    }
},
legend: {
    selectedMode: false
},
grid,
yAxis: {
    type: 'value'
},
xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
series
}; 实现思路与修改:

   
[*] 计算每天的总访问数:起首遍历 rawData 并计算每一天所有泉源的总访问数。这些总数被存储在 totalData 数组中。
[*] 配置每个数据源系列:为每一个数据源创建一个 series 对象。每个系列代表一种访问泉源,并包罗一些配置选项,如范例、堆叠设置、标签表现方式等。
[*] 配置标签表现:为了让用户在图表上直观地看到原始值和占比,我们必要在每个柱形上添加标签。标签的内容包罗原始值和百分比。
[*] 配置提示框(Tooltip):为了提供更丰富的信息,我们配置了一个提示框,当用户悬停在柱形上时会表现当天的总访问数和各个泉源的具体数值及占比。
 二开结果3:
https://i-blog.csdnimg.cn/direct/d9ec318b8bf54e588ef2a5dfbf1a1450.png
 完整版代码
// There should not be negative values in rawData
const rawData = [
,
,
,
,

];

const totalData = [];
for (let i = 0; i < rawData.length; ++i) {
let sum = 0;
for (let j = 0; j < rawData.length; ++j) {
    sum += rawData;
}
totalData.push(sum);
}

const grid = {
left: 100,
right: 100,
top: 50,
bottom: 50
};

const series = [
'Direct',
'Mail Ad',
'Affiliate Ad',
'Video Ad',
'Search Engine'
].map((name, sid) => {
return {
    name,
    type: 'bar',
    stack: 'total',
    barWidth: '60%',
    label: {
      show: true,
      position: 'inside', // Position the labels on top of the bars
      formatter: (params) => {
      const originalValue = rawData;
      const percentage = (originalValue / totalData * 100).toFixed(2);
      return `${originalValue} (${percentage}%)`;
      },
    },
    itemStyle: {
      emphasis: {
      // focus : 'series',
      label: {
          show: true,
          position: 'top',
          fontSize: 12,
          color: 'red',
          formatter: (params) => totalData
      }
      }
    },
    data: rawData.map((d, did) =>
      totalData <= 0 ? 0 : d / totalData
    )
};
});

option = {
legend: {
    selectedMode: false
},
grid,
yAxis: {
    type: 'value'
},
xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
series
}; 表明:

   

[*]添加了 itemStyle 选项,此中包罗了 emphasis 子项。
[*]在 emphasis 中设置了 label,用于在鼠标悬停时表现总值。
[*]emphasis.label.show 设为 true,表现在鼠标悬停时表现标签。
[*]emphasis.label.position 设为 'bottom',使标签表现在柱子底部。
[*]emphasis.label.fontSize 设为 12,调解字体巨细。
[*]emphasis.label.formatter 使用 totalData 表现当前柱子对应的总值
 柱状图转换为条形图
https://i-blog.csdnimg.cn/direct/64bad1bcb4034297bfd6a82511d0fb54.png
 核心代码修改,变更xAxis,yAxis 中的 x y 即可
 https://i-blog.csdnimg.cn/direct/aa73d9a058d2441e807c3148f02f5fc1.png
 条形图同时展示百分比、原始值、汇总值功能
// There should not be negative values in rawData
const rawData = [
,
,
,
,

];
const totalData = [];
for (let i = 0; i < rawData.length; ++i) {
let sum = 0;
for (let j = 0; j < rawData.length; ++j) {
    sum += rawData;
}
totalData.push(sum);
}
const grid = {
left: 100,
right: 100,
top: 50,
bottom: 50
};
const series = [
'Direct',
'Mail Ad',
'Affiliate Ad',
'Video Ad',
'Search Engine'
].map((name, sid) => {
return {
    name,
    type: 'bar',
    stack: 'total',
    barWidth: '60%',
    label: {
      show: true,
       position: 'inside',
      formatter: (params) => {
      const rawValue = rawData;
      const percentage = Math.round(params.value * 1000) / 10;
      return `${rawValue} \n(${percentage}%)`;
      }

    },
    data: rawData.map((d, did) =>
      totalData <= 0 ? 0 : d / totalData
    )
};
});
series.push({
    name: 'Total',
    type: 'bar',
    stack: 'total',
    itemStyle: {
      color: 'red' // 透明颜色
    },
    label: {
      show: true,
      // position: 'middle',
      formatter: params => `Total: ${totalData}`
    },
    data: totalData.map(value => 0.0) // 微小的值以便能显示标签但不影响图形
});
option = {
legend: {
    selectedMode: false
},
grid,
xAxis: {
    type: 'value'
},
yAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
series
};  结果展示

https://i-blog.csdnimg.cn/direct/b835167b7d394d72a7983eee9f89e97e.png

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Echarts 柱状图实现同时表现百分比+原始值+汇总值