Ohos-MPChart——支持多种图表绘制的组件

694 篇文章 18 订阅
504 篇文章 2 订阅

简介

Ohos-MPChart是OpenAtom OpenHarmony(简称“OpenHarmony”)系统显示各种图表视图的三方组件,用于声明式应用开发,提供了多种多样的图表视图,包括折线图、曲线图、柱形图、饼状图、K线图、雷达图、气泡图。适用于各种统计后的数据以视觉直观的方式呈现。

使用场景

Ohos-MPChart为广大OpenHarmony应用开发者在处理数据时,使数据显示更加直观。尤其现在的大数据时代面对愈加庞大的数据只需要导入Ohos-MPChart三方组件,然后调用相关的接口就能实现各种各样的图表以方便数据汇总。

效果展示

组件功能描述

Ohos-MPChart是一个强大的图表视图,主要提供多种多样的图表视图,包括折线图、曲线图、柱形图、饼状图、K线图等等,具体功能模块如下:

开发环境

安装IDE:支持DevEco Studio 3.0 Release(Build Version 3.0.0.993)版本。

安装SDK:支持OpenHarmony API version 8 及以上版本

使用方法

图表一:折线图

1.下载Ohos-MPChart组件并导入LineChart自定义组件:

//下载mpchart组件
 npm install @ohos/mpchart --save
import { LineChart } from '@ohos/ohos_mpchart'

2.初始化数据

aboutToAppear() {
    this.lineData = this.initCurveData(45, 100);
    this.topAxis.setLabelCount(5, false);
    this.topAxis.setPosition(XAxisPosition.TOP);
    this.topAxis.setAxisMinimum(0);
    this.topAxis.setAxisMaximum(50);
    this.bottomAxis.setLabelCount(5, false);
this.bottomAxis.setPosition(XAxisPosition.BOTTOM);
    this.bottomAxis.setAxisMinimum(0);
    this.bottomAxis.setAxisMaximum(50);
    this.bottomAxis.setDrawAxisLine(false);
    this.bottomAxis.setDrawLabels(false)
 
    this.leftAxis = new YAxis(AxisDependency.LEFT);
    this.leftAxis.setLabelCount(7, false);
    this.leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART);
    this.leftAxis.setSpaceTop(15);
    this.leftAxis.setAxisMinimum(-50);
    this.leftAxis.setAxisMaximum(200);
    this.leftAxis.enableGridDashedLine(5,5,0)
 
    this.rightAxis = new YAxis(AxisDependency.RIGHT);
    this.rightAxis.setDrawGridLines(false);
    this.rightAxis.setLabelCount(7, false);
    this.rightAxis.setSpaceTop(11);
    this.rightAxis.setAxisMinimum(-50); // this replaces setStartAtZero(true)
    this.rightAxis.setAxisMaximum(200);
    this.rightAxis.setDrawAxisLine(false);
 
    var upperLimtLine:LimitLine= new LimitLine(150, "Upper Limit");
    upperLimtLine.setLineWidth(4);
    upperLimtLine.enableDashedLine(10, 10, 0);
    upperLimtLine.setLabelPosition(LimitLabelPosition.RIGHT_TOP);
    upperLimtLine.setTextSize(10);
 
    var lowerLimtLine:LimitLine= new LimitLine(-30, "Lower Limit");
    lowerLimtLine.setLineWidth(4);
    lowerLimtLine.enableDashedLine(5, 5, 0);
    lowerLimtLine.setLabelPosition(LimitLabelPosition.RIGHT_BOTTOM);
    lowerLimtLine.setTextSize(10);
 
    this.leftAxis.setDrawLimitLinesBehindData(true);
    this.leftAxis.addLimitLine(upperLimtLine);
    this.leftAxis.addLimitLine(lowerLimtLine);
  }
  private initCurveData(count: number, range: number): LineData {
 
    let values = new JArrayList<EntryOhos>();
 
    for (let i = 0; i < 50; i++) {
      let val: number = Math.random() * 180-30;
      values.add(newEntryOhos(i, val));
}
 
let gradientFillColor =newArray<ColorStop>();
    gradientFillColor.push(['#ffff0000',0.1])
    gradientFillColor.push(['#00ff0000',1.0])
 
let dataSet =newJArrayList<ILineDataSet>();
 
let set1 =newLineDataSet(values,"DataSet 1");
    set1.setDrawFilled(true);
    set1.enableDashedLine(10,5,0)
    set1.setMode(Mode.LINEAR);
    set1.setGradientFillColor(gradientFillColor)
    set1.setColorByColor(Color.Black);
    set1.setLineWidth(1)
    set1.setDrawCircles(true);
    set1.setCircleColor(Color.Black);
    set1.setCircleRadius(2);
    set1.setCircleHoleRadius(1)
    set1.setCircleHoleColor(Color.Green)
    set1.setDrawCircleHole(false)
    dataSet.add(set1);
 
returnnewLineData(dataSet)
}

3.添加数据到自定义曲线图表组件

build() {
    Stack({ alignContent: Alignment.TopStart }) {
       LineChart({
        topAxis: this.topAxis,
        bottomAxis: this.bottomAxis,
        width: this.width,
        height: this.height,
        minOffset: this.minOffset,
        leftAxis: this.leftAxis,
        rightAxis: this.rightAxis,
        lineData: this.lineData,
      })
    }
  }

图表二:柱状图

1.导入BarChart自定义组件:

import{BarChart,BarChartModel} from '@ohos/ohos_mpchart'

2.初始化数据

@State model:BarChartModel = new BarChartModel();
  width: number = 350; //表的宽度
  height: number = 500; //表的高度
  minOffset: number = 15; //X轴线偏移量
  leftAxis: YAxis = null;
  rightAxis: YAxis = null;
  bottomAxis: XAxis = new XAxis();
 
  private aboutToAppear(){
    this.leftAxis = new YAxis(AxisDependency.LEFT);
    this.leftAxis.setLabelCount(6, false);
    this.leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART);
    this.leftAxis.setSpaceTop(15);
    this.leftAxis.setAxisMinimum(0);
    this.leftAxis.setAxisMaximum(110);
    this.leftAxis.enableGridDashedLine(10,10,0)
 
    this.rightAxis = new YAxis(AxisDependency.RIGHT);
    this.rightAxis.setDrawGridLines(false);
    this.rightAxis.setLabelCount(6, false);
    this.rightAxis.setSpaceTop(11);
    this.rightAxis.setAxisMinimum(0);
    this.rightAxis.setAxisMaximum(110);
 
    this.bottomAxis.setLabelCount(5, false);
    this.bottomAxis.setPosition(XAxisPosition.BOTTOM);
    this.bottomAxis.setAxisMinimum(0);
    this.bottomAxis.setAxisMaximum(10);
 
    this.setData(this.bottomAxis.getAxisMaximum(),this.leftAxis.getAxisMaximum())
 
    this.model.width = this.width;
    this.model.height = this.height;
    this.model.init();
    this.model.setDrawBarShadow(false);
    this.model.setDrawValueAboveBar(true);
    this.model.getDescription().setEnabled(false);
    this.model.setMaxVisibleValueCount(60);
    this.model.setLeftYAxis(this.leftAxis);
    this.model.setRightYAxis(this.rightAxis);
    this.model.setXAxis(this.bottomAxis)
    this.model.mRenderer.initBuffers();
    this.model.prepareMatrixValuePx();
  }
  private setData(count: number, range: number) {
    let groupSpace: number = 0.08;
    let barSpace: number = 0.03; // x4 DataSet
    let barWidth: number = 0.2; // x4 DataSet
    let groupCount: number = count + 1;
    let startYear: number = 1980;
    letendYear: number = startYear + groupCount;
letvalues1:JArrayList<BarEntry>=
newJArrayList<BarEntry>();
letvalues2:JArrayList<BarEntry>=
newJArrayList<BarEntry>();
letvalues3:JArrayList<BarEntry>=
newJArrayList<BarEntry>();
letvalues4:JArrayList<BarEntry>=
newJArrayList<BarEntry>();
letrandomMultiplier: number = range;
for(let i = startYear; i < endYear; i++){
      values1.add(newBarEntry(i,
(Math.random()* randomMultiplier)))
      values2.add(newBarEntry(i,
(Math.random()* randomMultiplier)))
      values3.add(newBarEntry(i,
(Math.random()* randomMultiplier)))
      values4.add(newBarEntry(i,
(Math.random()* randomMultiplier)))
}
letset1: BarDataSet,set2:
    BarDataSet,set3: BarDataSet,set4: BarDataSet;
if(this.model.getBarData()!=null&&
this.model.getBarData().getDataSetCount()>0){
      set1 =this.model.getBarData().getDataSetByIndex(0) as BarDataSet;
      set2 =this.model.getBarData().getDataSetByIndex(1) as BarDataSet;
      set3 =this.model.getBarData().getDataSetByIndex(2) as BarDataSet;
      set4 =this.model.getBarData().getDataSetByIndex(3) as BarDataSet;
      set1.setValues(values1);
      set2.setValues(values2);
      set3.setValues(values3);
      set4.setValues(values4);
this.model.getBarData().notifyDataChanged();
this.model.notifyDataSetChanged();
 
}else{
letcolors: number[]=
[Color.rgb(104,241,175),Color.rgb(164,228,251),Color.rgb(242,247,158),Color.rgb(255,102,0)];
      set1 =newBarDataSet(values1,"Company A");
      set1.setColorsByArr(colors);
      set2 =newBarDataSet(values2,"Company B");
      set2.setColorsByArr(colors);
      set3 =newBarDataSet(values3,"Company C");
      set3.setColorsByArr(colors);
      set4 =newBarDataSet(values2,"Company D");
      set4.setColorsByArr(colors);
 
letdataSets: JArrayList<IBarDataSet>=
newJArrayList<IBarDataSet>();
      dataSets.add(set1);
      dataSets.add(set2);
      dataSets.add(set3);
      dataSets.add(set4);
 
letdata: BarData =newBarData(dataSets);
this.model.setData(data);
}
this.model.getBarData().setBarWidth(barWidth);
this.bottomAxis.setAxisMinimum(startYear);
this.bottomAxis.setAxisMaximum(startYear +this.model.getBarData().getGroupWidth(groupSpace, barSpace)* groupCount);
this.model.groupBars(startYear, groupSpace, barSpace);
}

3.添加数据到自定义曲线图表组件

build() {
    Stack(){
      BarChart({model:this.model})
    }
  }

图表三:饼状图

1.导入PieChart自定义组件:

import { PieChart } from '@ohos/ohos_mpchart'

2.初始化数据

pieData: PieData = null;
  @State pieModel: PieChart.Model = new PieChart.Model()
  @State @Watch("seekBarXValueWatch")
  seekBarX: SeekBar.Model = new SeekBar.Model()
  @State @Watch("seekBarYValueWatch")
  seekBarY: SeekBar.Model = new SeekBar.Model()
  parties: string[] = [
    "Party A", "Party B", "Party C", "Party D", "Party E", "Party F", "Party G", "Party H",
    "Party I", "Party J", "Party K", "Party L", "Party M", "Party N", "Party O", "Party P",
    "Party Q", "Party R", "Party S", "Party T", "Party U", "Party V", "Party W", "Party X",
    "Party Y", "Party Z"]
 
  private aboutToAppear(): void {
    this.pieData = this.initPieData(4, 10);
    this.pieModel
      .setPieData(this.pieData)
      .setRadius(150)
      .setHoleRadius(0.5)
      .setOffset(new MPPointF(160,200))   // vp
  }
  private initPieData(count: number,
  range: number): PieData{
    let entries = new JArrayList<PieEntry>();
    for (var i = 0; i < count; i++) {
      entries.add(new PieEntry(((Math.random() * range) + range / 5), this.parties[i % this.parties.length]))
    }
    //        entries.add(new PieEntry(4,'Party A'))
    //        entries.add(new PieEntry(2,'Party B'))
    //        entries.add(new PieEntry(5,'Party C'))
    //        entries.add(new PieEntry(3,'Party D'))
 
    let dataSet: PieDataSet = new PieDataSet(entries,
     "Election Results");
    dataSet.setDrawIcons(false);
    dataSet.setSliceSpace(3);
    dataSet.setIconsOffset(new MPPointF(0, 40));
    dataSet.setSelectionShift(5);
 
    // add a lot of colors
    let colors: JArrayList<number> = new JArrayList();
    for (let index = 0;
    index < ColorTemplate.VORDIPLOM_COLORS.length; index++) {
      colors.add(ColorTemplate.VORDIPLOM_COLORS[index]);
    }
 
    for(let index =0;
    index < ColorTemplate.JOYFUL_COLORS.length; index++){
      colors.add(ColorTemplate.JOYFUL_COLORS[index]);
}
 
for(let index =0;
    index < ColorTemplate.COLORFUL_COLORS.length; index++){
      colors.add(ColorTemplate.COLORFUL_COLORS[index]);
}
for(let index =0;
    index < ColorTemplate.LIBERTY_COLORS.length; index++){
      colors.add(ColorTemplate.LIBERTY_COLORS[index]);
}
for(let index =0;
    index < ColorTemplate.PASTEL_COLORS.length; index++){
      colors.add(ColorTemplate.PASTEL_COLORS[index]);
}
    colors.add(ColorTemplate.getHoloBlue());
    dataSet.setColorsByList(colors);
returnnewPieData(dataSet)
}

3.添加数据到自定义曲线图表组件

build() {
    Column() {
      PieChart({
        model: this.pieModel
      }) 
}

图表四:雷达图

1.导入RadarChart自定义组件:

import { RadarChart } from '@ohos/ohos_mpchart';

2.初始化数据

width: number = 300; //表的宽度
  height: number = 300 //表的高度
  minOffset: number = 5; //X轴线偏移量
  xAxis: XAxis = new XAxis(); //顶部X轴
  yAxis: YAxis = new YAxis();
  data:RadarData= new RadarData();
  @State
  radarChartMode:RadarChartMode=new RadarChartMode();
public aboutToAppear() {
    this.model.menuItemArr = this.menuItemArr
    this.model.title = this.title
 
    this.data=this.initRadarData( 5,50)
    this.xAxis.setTextSize(9);
    this.xAxis.setYOffset(0);
    this.xAxis.setXOffset(0);
    this.xAxis.setTextColor(Color.White);
    const mActivities:string[] = ["Burger", "Steak", "Salad", "Pasta", "Pizza"];
    this.xAxis.setValueFormatter(new
    class RadarAxisValueFormatter
    implements IAxisValueFormatter{
      public  getFormattedValue( value:number,
        axis:AxisBase):string {
        return mActivities[value % mActivities.length];
      }
    });
    this.xAxis.longest=mActivities[0];
    this.yAxis.setLabelCount(5, false);
    this.yAxis.setTextSize(9);
    this.yAxis.setAxisMinimum(0);
    this.yAxis.setAxisMaximum(80);
    this.yAxis.setDrawLabels(false);
 
    this.radarChartMode.mRotateEnabled=false
    this.radarChartMode.setYExtraOffset(this.model.height)
    this.radarChartMode.setXAxis(this.xAxis)
    this.radarChartMode.setYAxis(this.yAxis)
    this.radarChartMode.setWidth(this.width)
    this.radarChartMode.setHeight(this.height)
    this.radarChartMode.setMinOffset(this.minOffset)
    this.radarChartMode.setData(this.data)
    this.radarChartMode.setPaddingLeft(30)
    this.radarChartMode.setPaddingTop(100)
    this.radarChartMode.init();
    //this.animate('Animate XY')
  }
 
  private initRadarData(count: number,
  range: number): RadarData {
    let mul:number = 80;
    let min:number = 20;
    let cnt:number =5;
let entries1 =newJArrayList<RadarEntry>();
let entries2 =newJArrayList<RadarEntry>();
 
//NOTE: The order of the entries when being added to the entries array determines their position around the center of
// the chart.
for(let i =0; i < cnt; i++){
letval1:number = Math.random()* mul + min;
      entries1.add(newRadarEntry(val1));
 
letval2:number = Math.random()* mul + min;
      entries2.add(newRadarEntry(val2));
}
letset1:RadarDataSet =newRadarDataSet(entries1,
"Last Week");
    set1.setColorByColor(0xb4676e81);
    set1.setFillColor(0xb4676e81);
    set1.setDrawFilled(true);
    set1.setFillAlpha(180);
    set1.setLineWidth(2);
    set1.setDrawHighlightCircleEnabled(true);
    set1.setDrawHighlightIndicators(false);
    set1.setHighlightCircleStrokeColor(0xffffffff);
    set1.setHighlightCircleFillColor(0xb4676e81)
    set1.setDrawValues(true)
    set1.setIconsOffset(newMPPointF(0,px2vp(0)));
 
letset2:RadarDataSet =newRadarDataSet(entries2,"This Week");
    set2.setColorByColor(0xb479a2af);
    set2.setFillColor(0xb479a2af);
    set2.setDrawFilled(true);
    set2.setFillAlpha(180);
    set2.setLineWidth(2);
    set2.setDrawHighlightCircleEnabled(true);
    set2.setDrawHighlightIndicators(false);
    set2.setHighlightCircleStrokeColor(0xffffffff);
    set2.setHighlightCircleFillColor(0xb479a2af)
    set2.setDrawValues(true)
    set2.setIconsOffset(newMPPointF(0,px2vp(0)));
 
let sets =newJArrayList<IRadarDataSet>();
    sets.add(set1);
    sets.add(set2);
//
letdata:RadarData =newRadarData(sets);
    data.setValueTextSize(8);
    data.setDrawValues(this.isDrawValuesEnable);
    data.setValueTextColor(Color.White);
return data
}
  public getFormattedValue(value: number): string {
    var str =String(value.toFixed(1)).split(".");
if(str[1]=="0"){
return str[0];
}else{
returnString(value.toFixed(1))
}
}

3.添加数据到自定义曲线图表组件

build() {
    Column() {
      Stack({ alignContent: Alignment.TopStart }) {
        RadarChart({
          radarChartMode:this.radarChartMode,
        })
      }
    }
  }

其他图表使用方式与以上图表使用方法基本一致

为了帮助到大家能够更有效的学习OpenHarmony 开发的内容,下面特别准备了一些相关的参考学习资料:

OpenHarmony 开发环境搭建:https://qr18.cn/CgxrRy

《OpenHarmony源码解析》:https://qr18.cn/CgxrRy

  • 搭建开发环境
  • Windows 开发环境的搭建
  • Ubuntu 开发环境搭建
  • Linux 与 Windows 之间的文件共享
  • ……

系统架构分析:https://qr18.cn/CgxrRy

  • 构建子系统
  • 启动流程
  • 子系统
  • 分布式任务调度子系统
  • 分布式通信子系统
  • 驱动子系统
  • ……

OpenHarmony 设备开发学习手册:https://qr18.cn/CgxrRy

在这里插入图片描述

OpenHarmony面试题(内含参考答案):https://qr18.cn/CgxrRy

Android MPChart是一款功能强大的开源图表库,用于在Android应用中显示各种类型的图表。 MPChart支持多种类型的图表,包括折线图、柱状图、饼图、雷达图等。它可以轻松地将数据以图表的形式展示出来,帮助用户更直观地理解数据。 使用MPChart库非常简单。首先,我们需要在项目中引入MPChart库的依赖。在build.gradle文件中添加相关依赖后,就可以使用MPChart库的功能了。 接下来,我们需要创建一个图表对象,并为其设置相应的数据源。例如,如果要创建一个柱状图,我们可以使用BarChart类,并通过setData()方法设置柱状图的数据。 在设置完数据源之后,我们可以通过一些自定义的方法对图表进行个性化设置。例如,可以设置图表的颜色、字体、边框等样式,以及设置相应的动画效果。 最后,我们需要将图表对象添加到布局文件中,让其显示在界面上。我们可以通过在布局文件中添加一个ChartView视图,然后通过findViewById()方法获取该视图,并将图表对象设置给它。 使用MPChart库可以轻松地创建出漂亮、交互性强的图表。同时,MPChart库还提供了一些有用的功能,如缩放、滑动、手势操作等,方便用户在查看数据时进行细致的操作。 总的来说,Android MPChart是一款功能强大、易于使用的图表库,可以帮助开发者在Android应用中展示各种类型的图表,并提供丰富的自定义选项和交互功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值