MPAndroidChart3图表库的使用

现在网上很多大神写的都是2.x版本的,3版本改动比较大,刚换3时我也摸不着头脑。

一、概述

MPAndroidChart 是一款专门用于Android绘制图表的库,有android和IOS版本,我是看到他两个平台都有才使用的,当然,这个图表库自身也足够强大,足以满足日常的图表展示。

图表库原始地址在这里点击打开链接,英文好的同学,以及不想看本渣渣的同学可以直接去原始地址查看,贼强大。

 
  

核心功能

  • 支持以下图表:
    • Line Chart(线图)
    • Bar Chart(条形图,又称柱状图)
    • Combined Chart(组合图:线性+条形)
    • Pie Chart(饼状图)
    • Scatter Chart(散点图)
    • Bubble Chart(气泡图)
    • Stacked Bar Chart(堆积条形图)
    • Candle Stick Chart(蜡烛图)
    • Cubic Line Chart(立方拟合的折线图)
    • Radar Chart(雷达图)
    • Realtime Chart(实时折线图)
    • Sinus Bar Chart(正弦柱状图)
  • 支持以下操作和设置:
    • 支持x,y轴缩放
    • 支持拖拽
    • 支持手指滑动
    • 支持高亮显示
    • 支持保存图表到文件中
    • 支持从文件(txt)中读取数据
    • 预先定义颜色模板
    • 自动生成标注
    • 支持自定义x,y轴的显示标签
    • 支持x,y轴动画
    • 支持x,y轴设置最大值和附加信息
    • 支持自定义字体,颜色,背景,手势,虚线等
二、集成

集成很简单,原文也有介绍3种方法,喜欢jar包集成的同学直接网上搜索jar包。原文介绍的三种方法如下:

1. Gradle dependency (recommended)

  • Add the following to your project level build.gradle:
allprojects {
	repositories {
		maven { url "https://jitpack.io" }
	}
}
  • Add this to your app build.gradle:
dependencies {
	implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
}

2. Maven

  • Add the following to the  section of your pom.xml:
<repository>
       <id>jitpack.ioid>
       <url>https://jitpack.iourl>
repository>
  • Add the following to the  section of your pom.xml:
<dependency>
       <groupId>com.github.PhilJaygroupId>
       <artifactId>MPAndroidChartartifactId>
       <version>v3.0.3version>
dependency>

3. clone whole repository (not recommended)

好了,我们用第一种。

在包的build.gradle添加如下:

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
    }
}
在模板的build.gradle添加

dependencies {
    compile 'com.github.PhilJay:MPAndroidChart:v3.0.2'
}
最新的已经有3.0.3,但是我引入3.0.3的时候有错误,引入3.0.2没问题。

这样就集成好了。

三、使用

这里我先介绍折线图的使用。

创建折线图有两种方法,一种在xml里面添加,一种直接代码创建,本渣渣用的第一种。so:

<com.github.mikephil.charting.charts.LineChart
    android:id="@+id/Chart_Heart"
    android:layout_width="0dp"
    android:layout_height="220dp"
    android:layout_marginBottom="16dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent" />
然后代码里面初始化:

 private void LinChart(){
        mChart = getView().findViewById(R.id.Chart_Heart);
        mChart.setNoDataText("");
        //设置右下角描述
        Description a = new Description();
        a.setText("");
        mChart.setDescription(a);

        mChart.setTouchEnabled(true);

        // 可拖曳
        mChart.setDragEnabled(true);

        // 可缩放
        mChart.setScaleEnabled(true);
        //不显示表格颜色
        mChart.setDrawGridBackground(false);

        mChart.setPinchZoom(true);

        // 设置图表的背景颜色
        //mChart.setBackgroundColor(Color.LTGRAY);

        LineData data = new LineData();

        // 数据显示的颜色
        // data.setValueTextColor(Color.BLUE);

        // 先增加一个空的数据,随后往里面动态添加
        mChart.setData(data);

        // 图表的注解(只有当数据集存在时候才生效)
        Legend l = mChart.getLegend();

        // 可以修改图表注解部分的位置
        // l.setPosition(LegendPosition.LEFT_OF_CHART);

        // 线性,也可是圆
        l.setForm(Legend.LegendForm.CIRCLE);
// 颜色
        l.setTextColor(Color.WHITE);

        // x坐标轴
        XAxis xl = mChart.getXAxis();
        xl.setTextColor(Color.BLACK);
        xl.setDrawGridLines(false);
        xl.setAvoidFirstLastClipping(true);

        xl.setYOffset(-12);
        xl.setLabelCount(5, false);
        // 如果false,那么x坐标轴将不可见
        xl.setEnabled(true);

        // 将X坐标轴放置在底部,默认是在顶部。
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);

//        xl.setValueFormatter(new IAxisValueFormatter() {
//            @Override
//            public String getFormattedValue(float value, AxisBase axis) {
//                return timeList.get((int)value);
//            }
//        });

        // 图表左边的y坐标轴线
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setTextColor(Color.BLACK);

//    // 最大值
        leftAxis.setAxisMaxValue(220f);
//
//    // 最小值
        leftAxis.setAxisMinValue(40f);

        // 不一定要从0开始
        leftAxis.setStartAtZero(false);

        leftAxis.setDrawGridLines(true);

        YAxis rightAxis = mChart.getAxisRight();
        // 不显示图表的右边y坐标轴线
        rightAxis.setEnabled(false);
    }
就ok了,我这里需要动态添加数据所以添加数据这么写:

private void addEntry(int f) {

    LineData data = mChart.getData();

    // 每一个LineDataSet代表一条线,每张统计图表可以同时存在若干个统计折线,这些折线像数组一样从0开始下标。
    // 本例只有一个,那么就是第0条折线
    LineDataSet set = (LineDataSet) data.getDataSetByIndex(0);

    // 如果该统计折线图还没有数据集,则创建一条出来,如果有则跳过此处代码。
    if (set == null) {
        set = createLineDataSet();
        data.addDataSet(set);
    }

    // 先添加一个x坐标轴的值
    // 因为是从0开始,data.getXValCount()每次返回的总是全部x坐标轴上总数量,所以不必多此一举的加1
   timeList.add(df.format(new Date(new Date().getTime()))+ "");
    Entry entry = new Entry(set.getEntryCount(),f);

    data.addEntry(entry, 0);

    // 像ListView那样的通知数据更新
    data.notifyDataChanged();

    mChart.notifyDataSetChanged();

    mChart.getXAxis().setValueFormatter(mIA);

    // 当前统计图表中最多在x轴坐标线上显示的总量
    mChart.setVisibleXRangeMaximum(50);

    // y坐标轴线最大值
    // mChart.setVisibleYRange(30, AxisDependency.LEFT);

    // 将坐标移动到最新
    // 此代码将刷新图表的绘图
    mChart.moveViewToX(data.getDataSetCount() - 50);

    // mChart.moveViewTo(data.getXValCount()-7, 55f,
    // AxisDependency.LEFT);
}
x轴数据写法跟以前不一样了,我这里x轴用的添加数据的时间:

SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//设置日期格式
private List timeList = new ArrayList<>(); //存储x轴的时间

IAxisValueFormatter mIA = new IAxisValueFormatter() {
    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        return timeList.get((int) value);
    }
};
好了,完成。主要是给自己做个备忘,记性太差。以后再要用到的时候翻博客就OK啦。

你可能感兴趣的:(Android)