在条形图中呈现数据AngularJS,如何制作一个好的多条形图

Presenting Data in a bar chart AngularJS, How to make a good multi-bar chart?

本文关键字:条形图 一个 好的多 何制作 数据 AngularJS      更新时间:2023-09-26

假设我有以下JSON:

[
        {
            month: "Jan",
            cost: 80,
            energy: 90
        },
        {
            month: "Feb",
            cost: 50,
            energy: 80
        },
        {
            month: "Mar",
            cost: 90,
            energy: 40
        },
        {
            month: "Apr",
            cost: 80,
            energy: 90
        },
        {
            month: "May",
            cost: 50,
            energy: 80
        },
        {
            month: "Jun",
            cost: 70,
            energy: 40
        },
        {
            month: "Jul",
            cost: 40,
            energy: 70
        },
        {
            month: "Aug",
            cost: 80,
            energy: 90
        },
        {
            month: "Sep",
            cost: 90,
            energy: 90
        },
        {
            month: "Oct",
            cost: 40,
            energy: 90
        },
        {
            month: "Nov",
            cost: 20,
            energy: 50
        },
        {
            month: "Dec",
            cost: 10,
            energy: 20
        },
    ];

如何在我的网站上以简单的条形图的形式显示?

  • Y轴作为成本/能源的数字刻度
  • X轴显示月份

我曾在以下指南中尝试过纯使用CSS和Javascript,但该解决方案非常基本,一次只显示一条数据(即一个月内的成本或能量)。

以下是我尝试过的一个例子:HTML

<ul class="chart" style="width:{{width}}px; height:{{height}}px;" >
      <div class="y" style="width:{{height}}px;">{{yAxis}}</div>
      <div class="x">{{xAxis}}</div>
      <li ng-repeat="bar in data" class="bar" style="height:{{bar.cost / max * height}}px; width:{{width / data.length - 5}}px; left:{{$index / data.length * width}}px;"><span>{{bar.month}}:{{bar.cost}}</span></li>
    </ul>

控制器:

    $scope.width = 600;
    $scope.height = 400;
    $scope.yAxis = "Amount";
    $scope.xAxis = "Month";
    $scope.data = dataService.usage;
    $scope.max = dataService.max;
// Dataservice is a factory which returns the aformentioned JSON

CSS:

.chart {
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  margin: 60px auto;
  position: relative;
}
.y {
  position: absolute;
  transform: rotate(-90deg);
  transform-origin: bottom left;
  bottom: 0;
  padding: 5px;
}
.x {
  position: absolute;
  top: 100%;
  width: 100%;
  padding: 5px;
}
.bar {
  background: blue;
  position: absolute;

 bottom: 0;
}

这种方法在页面上看起来很糟糕,Y轴也没有正确显示。

有没有更好的方法在Angular中显示我的数据?

您可能需要使用图表库。