草庐IT

通过Echarts怎样实现立体柱状图

梁木由 2024-02-27 原文

前言

大家好,我是梁木由。之前在做大屏可视化项目时,UI设计了一个立体形状的柱状图,根据之前做的一些图表的项目没有能复用的,没有做过这种立体形状的图表,打开echarts也没看到有相关的demo,看下如何实现

图表样例

来看下UI设计师给到的设计图

上述设计图种柱状图都是立体的样式,那我们来看下如何实现

实现方法

先写一个常规的柱状图

在这个基础上进行改进

<div id="main"></div>
​
#main{
  width: 500px;
  height: 350px;
}
​
var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;
​
option = {
  xAxis: {
    axisTick: {
      show: false
    },
    nameTextStyle: {
      color: '#fff'
    },
    data: ['春节', '元宵节', '端午节', '中秋节']
  },
  legend: {
    data: ['春节', '元宵节', '端午节', '中秋节'],
    right: '25',
    top: '18',
    icon: 'rect',
    itemHeight: 10,
    itemWidth: 10,
    textStyle: {
      color: '#000'
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      color: '#000'
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: ['#ccc']
      }
    }
  },
  series: [
    {
      data: [
        { name: '春节', value: 24 },
        { name: '端午节', value: 44 },
        { name: '中秋节', value: 32 },
        { name: '春节', value: 50 }
      ],
      barWidth: 30,
      type: 'bar'
    }
  ]
};
​
​
option && myChart.setOption(option);

echarts的配置选项

首先呢我们看下echarts的配置选项

那我们看所有的type 没有立体柱状图的类型,但是呢我们看最后一项type: custom,什么意思呢,自定义系列,那就是说我们可以选择custom 类型来实现立体柱状图

renderItem

type为custom可以自定义系列图形元素渲染。

根据查看配置项,发现有一个renderItem函数,custom 系列需要开发者自己提供图形渲染的逻辑。这个渲染逻辑一般命名为 renderItem

看下renderItem函数的介绍

renderItem 函数提供了两个参数:

  • params:包含了当前数据信息和坐标系的信息。

    • {
          context: // {Object} 一个可供开发者暂存东西的对象。生命周期只为:当前次的渲染。
          seriesId: // {string} 本系列 id。
          seriesName: // {string} 本系列 name。
          seriesIndex: // {number} 本系列 index。
          dataIndex: // {number} 数据项的 index。
          dataIndexInside: // {number} 数据项在当前坐标系中可见的数据的 index(即 dataZoom 当前窗口中的数据的 index)。
          dataInsideLength: // {number} 当前坐标系中可见的数据长度(即 dataZoom 当前窗口中的数据数量)。
          actionType: // {string} 触发此次重绘的 action 的 type。
          coordSys: // 不同的坐标系中,coordSys 里的信息不一样,含有如下这些可能:
          coordSys: {
              type: 'cartesian2d',
              x: // {number} grid rect 的 x
              y: // {number} grid rect 的 y
              width: // {number} grid rect 的 width
              height: // {number} grid rect 的 height
          },
          coordSys: {
              type: 'calendar',
              x: // {number} calendar rect 的 x
              y: // {number} calendar rect 的 y
              width: // {number} calendar rect 的 width
              height: // {number} calendar rect 的 height
              cellWidth: // {number} calendar cellWidth
              cellHeight: // {number} calendar cellHeight
              rangeInfo: {
                  start: // calendar 日期开端
                  end: // calendar 日期结尾
                  weeks: // calendar 周数
                  dayCount: // calendar 日数
              }
          },
          coordSys: {
              type: 'geo',
              x: // {number} geo rect 的 x
              y: // {number} geo rect 的 y
              width: // {number} geo rect 的 width
              height: // {number} geo rect 的 height
              zoom: // {number} 缩放的比率。如果没有缩放,则值为 1。例如 0.5 表示缩小了一半。
          },
          coordSys: {
              type: 'polar',
              cx: // {number} polar 的中心坐标
              cy: // {number} polar 的中心坐标
              r: // {number} polar 的外半径
              r0: // {number} polar 的内半径
          },
          coordSys: {
              type: 'singleAxis',
              x: // {number} singleAxis rect 的 x
              y: // {number} singleAxis rect 的 y
              width: // {number} singleAxis rect 的 width
              height: // {number} singleAxis rect 的 height
          }
      }
      
    • 其中,关于 dataIndexdataIndexInside 的区别:

      • dataIndex 指的 dataItem 在原始数据中的 index。
      • dataIndexInside 指的是 dataItem 在当前数据窗口中的 index。

      [renderItem.arguments.api] 中使用的参数都是 dataIndexInside 而非 dataIndex,因为从 dataIndex 转换成 dataIndexInside 需要时间开销。

  • api:是一些开发者可调用的方法集合。

    • 所有属性

      {[value], [coord] , [size] , [style] , [styleEmphasis] , [visual] , [barLayout] , [currentSeriesIndices] , [font], [getWidth] , [getHeight], [getZr], [getDevicePixelRatio]}

我们使用renderItem来自定义元素会使用到renderItem.api的三个方法,先来介绍下这三个方法

  • [api.value(…)],意思是取出 dataItem 中的数值。例如 api.value(0) 表示取出当前 dataItem 中第一个维度的数值。
  • [api.coord(…)],意思是进行坐标转换计算。例如 var point = api.coord([api.value(0), api.value(1)]) 表示 dataItem 中的数值转换成坐标系上的点。
  • [api.size(…)] ,表示得到坐标系上一段数值范围对应的长度。

看下代码实现

series:  getSeriesData()
​
function getSeriesData() {
  const data = [];
  seriesData.forEach((item, index) => {
    data.push(
      {
        type: 'custom',
        name: item.label,
        renderItem: function (params, api) {
          return getRenderItem(params, api);
        },
        data: item.value,
      }
    )
  })
  return data
}
​
function getRenderItem(params, api) {
  // params.seriesIndex表示本系列 index
  const index = params.seriesIndex;
  // api.coord() 坐标转换计算
  // api.value() 取出当前项中的数值
  let location = api.coord([api.value(0) + index, api.value(1)]);
  // api.size() 坐标系数值范围对应的长度
  var extent = api.size([0, api.value(1)]);
  return {
    type: 'rect',
    shape: {
      x: location[0] - 20 / 2,
      y: location[1],
      width: 20,
      height: extent[1]
    },
    style: api.style()
  };
}

来看下我们的实现效果

柱状图效果出来了,那来看下怎么将柱状图改为立体图

return_group

我看到renderItem可以返回一个return_group类型,来看看这个类型的介绍

  • group 是唯一的可以有子节点的容器。
  • group 可以用来整体定位一组图形元素。

那就是说我们可以将设定一组图形元素然后组合到一起形成立体柱状图

那么问题又来了怎么设定一组图形元素呢?

graphic

这个呢是关于图形相关的方法,再来了解两个API

graphic.extendShape

创建一个新的图形元素

graphic.registerShape

注册一个开发者定义的图形元素

创建图形元素

那我们先来创建一个新的图形元素

const leftRect = echarts.graphic.extendShape({
    shape: {
      x: 0,
      y: 0,
      width: 19, //柱状图宽
      zWidth: 8, //阴影折角宽
      zHeight: 4, //阴影折角高
    },
    buildPath: function (ctx, shape) {
      const api = shape.api;
      const xAxisPoint = api.coord([shape.xValue, 0]);
      const p0 = [shape.x - shape.width / 2, shape.y - shape.zHeight];
      const p1 = [shape.x - shape.width / 2, shape.y - shape.zHeight];
      const p2 = [xAxisPoint[0] - shape.width / 2, xAxisPoint[1]];
      const p3 = [xAxisPoint[0] + shape.width / 2, xAxisPoint[1]];
      const p4 = [shape.x + shape.width / 2, shape.y];
​
      ctx.moveTo(p0[0], p0[1]); 
      ctx.lineTo(p1[0], p1[1]);
      ctx.lineTo(p2[0], p2[1]);
      ctx.lineTo(p3[0], p3[1]);
      ctx.lineTo(p4[0], p4[1]);
      ctx.lineTo(p0[0], p0[1]);
      ctx.closePath();
    },
  });
​
​
const rightRect = echarts.graphic.extendShape({
    shape: {
      x: 0,
      y: 0,
      width: 18,
      zWidth: 15,
      zHeight: 8,
    },
    buildPath: function (ctx, shape) {
      const api = shape.api;
      const xAxisPoint = api.coord([shape.xValue, 0]);
      const p1 = [shape.x - shape.width / 2, shape.y - shape.zHeight / 2];
      const p3 = [xAxisPoint[0] + shape.width / 2, xAxisPoint[1]];
      const p4 = [shape.x + shape.width / 2, shape.y];
      const p5 = [xAxisPoint[0] + shape.width / 2 + shape.zWidth, xAxisPoint[1]];
      const p6 = [shape.x + shape.width / 2 + shape.zWidth, shape.y - shape.zHeight / 2];
      const p7 = [shape.x - shape.width / 2 + shape.zWidth, shape.y - shape.zHeight];
      ctx.moveTo(p4[0], p4[1]); 
      ctx.lineTo(p3[0], p3[1]);
      ctx.lineTo(p5[0], p5[1]);
      ctx.lineTo(p6[0], p6[1]);
      ctx.lineTo(p4[0], p4[1]);
​
      ctx.moveTo(p4[0], p4[1]);
      ctx.lineTo(p6[0], p6[1]);
      ctx.lineTo(p7[0], p7[1]);
      ctx.lineTo(p1[0], p1[1]);
      ctx.lineTo(p4[0], p4[1]);
      ctx.closePath();
    },
  });

注册图形元素

echarts.graphic.registerShape('leftRect', leftRect);
echarts.graphic.registerShape('rightRect', rightRect);

再来修改一下return_group

function getRenderItem(params, api) {
  const index = params.seriesIndex;
  let location = api.coord([api.value(0) + index, api.value(1)]);
  var extent = api.size([0, api.value(1)]);
  return {
    type: 'group',
    children: [
      {
        type: 'leftRect',
        shape: {
          api,
          xValue: api.value(0) + index,
          yValue: api.value(1),
          x: location[0],
          y: location[1]
        },
        style: api.style()
      },
      {
        type: 'rightRect',
        shape: {
          api,
          xValue: api.value(0) + index,
          yValue: api.value(1),
          x: location[0],
          y: location[1]
        },
        style: api.style()
      }
    ]
  };
}

再来看下效果

可以看到立体形状的柱状图已经实现了,那还有个缺点就是颜色需要再按照设计图来改改

const colors = [
    [
      { offset: 0, color: 'rgba(26, 132, 191, 1)' },
      { offset: 1, color: 'rgba(52, 163, 224, 0.08)' },
    ],
    [
      { offset: 0, color: 'rgba(137, 163, 164, 1)' },
      { offset: 1, color: 'rgba(137, 163, 164, 0.08)' },
    ],
    [
      { offset: 0, color: 'rgba(44, 166, 166, 1)' },
      { offset: 1, color: 'rgba(44, 166, 166, 0.08)' },
    ],
    [
      { offset: 0, color: 'rgba(34, 66, 186, 1)' },
      { offset: 1, color: 'rgba(34, 66, 186, 0.08)' },
    ],
  ];
​
//在getSeriesData添加itemStyle
itemStyle: {
       color: () => {
              return new echarts.graphic.LinearGradient(0, 0, 0, 1, colors[index]);
       },
},

效果图

结尾

Echarts实现立体柱状图——码上掘金

如果文章对你有帮助,期望点一下赞支持一下,🙏🙏🙏

有关通过Echarts怎样实现立体柱状图的更多相关文章

  1. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  2. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  3. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  4. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  5. ruby-on-rails - Enumerator.new 如何处理已通过的 block ? - 2

    我在理解Enumerator.new方法的工作原理时遇到了一些困难。假设文档中的示例:fib=Enumerator.newdo|y|a=b=1loopdoy[1,1,2,3,5,8,13,21,34,55]循环中断条件在哪里,它如何知道循环应该迭代多少次(因为它没有任何明确的中断条件并且看起来像无限循环)? 最佳答案 Enumerator使用Fibers在内部。您的示例等效于:require'fiber'fiber=Fiber.newdoa=b=1loopdoFiber.yieldaa,b=b,a+bendend10.times.m

  6. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  7. ruby-on-rails - 如果我将 ruby​​ 版本 2.5.1 与 rails 版本 2.3.18 一起使用会怎样? - 2

    如果我使用ruby​​版本2.5.1和Rails版本2.3.18会怎样?我有基于rails2.3.18和ruby​​1.9.2p320构建的rails应用程序,我只想升级ruby的版本,而不是rails,这可能吗?我必须面对哪些挑战? 最佳答案 GitHub维护apublicfork它有针对旧Rails版本的分支,有各种变化,它们一直在运行。有一段时间,他们在较新的Ruby版本上运行较旧的Rails版本,而不是最初支持的版本,因此您可能会发现一些关于需要向后移植的有用提示。不过,他们现在已经有几年没有使用2.3了,所以充其量只能让更

  8. ruby - 寻找通过阅读代码确定编程语言的ruby gem? - 2

    几个月前,我读了一篇关于ruby​​gem的博客文章,它可以通过阅读代码本身来确定编程语言。对于我的生活,我不记得博客或gem的名称。谷歌搜索“ruby编程语言猜测”及其变体也无济于事。有人碰巧知道相关gem的名称吗? 最佳答案 是这个吗:http://github.com/chrislo/sourceclassifier/tree/master 关于ruby-寻找通过阅读代码确定编程语言的rubygem?,我们在StackOverflow上找到一个类似的问题:

  9. 通过 MacPorts 的 RubyGems 是个好主意吗? - 2

    从MB升级到新的MBP后,Apple的迁移助手没有移动我的gem。我这次是通过macports安装ruby​​gems,希望在下次升级时避免这种情况。有什么我应该注意的陷阱吗? 最佳答案 如果你想把你的gems安装在你的主目录中(在传输过程中应该复制过来,作为一个附带的好处,会让你以你自己的身份运行geminstall,而不是root),将gemhome:键设置为您在~/.gemrc中的主目录中的路径. 关于通过MacPorts的RubyGems是个好主意吗?,我们在StackOverf

  10. ruby - 通过 RVM 安装 Ruby 1.9.2 永远行不通! - 2

    当我执行>rvminstall1.9.2时一切顺利。然后我做>rvmuse1.9.2也很顺利。但是当涉及到ruby​​-v时..sam@sjones:~$rvminstall1.9.2/home/sam/.rvm/rubies/ruby-1.9.2-p136,thismaytakeawhiledependingonyourcpu(s)...ruby-1.9.2-p136-#fetchingruby-1.9.2-p136-#downloadingruby-1.9.2-p136,thismaytakeawhiledependingonyourconnection...%Total%Rece

随机推荐