如何使用 MPAndroidChart 畫圖,以折線圖為例

栏目: 编程工具 · 发布时间: 7年前

内容简介:加上以下設定,project 的 build.gradle:module 的 build.gradle:

MPAndroidChart 是 Android 熱門畫圖表的函式庫之一,這邊簡單示範一下要如何用 MPAndroidChart 畫一張折線圖(Line Chart)。

Gradle 設定

加上以下設定,project 的 build.gradle:

allprojects {
    repositories {
         ...
        maven { url "https://jitpack.io" }
    }
}

module 的 build.gradle:

dependencies {
    ...
    compile 'com.github.PhilJay:MPAndroidChart:v2.1.3'
}

畫一個簡單的 Line Chart

以下,我在網路上找了一張

首先在 layout 檔案加上一個 LineChart, id 命名為 @+id/chart

<com.github.mikephil.charting.charts.LineChart
    android:id="@+id/chart"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

在 onCreate() 中把 chart 抓出來,就可以開始設定了

LineChart chart = (LineChart) findViewById(R.id.chart);

接下來就可以準備把資料給塞進去了,一張 chart 可以有很多個 dataset ,而每一個 dataset 則包含多個資料點,最後再把這在 dataset 包在一個 chart 中,如下

String dataset_label1 = "Company 1";
    ArrayList<Entry> yVals1 = new ArrayList<>();
    yVals1.add(new Entry(100, 0));
    yVals1.add(new Entry(105, 1));
    yVals1.add(new Entry(100, 2));
    yVals1.add(new Entry(250, 3));
    LineDataSet dataSet1 = new LineDataSet(yVals1, dataset_label1);
    dataSet1.setColors(ColorTemplate.VORDIPLOM_COLORS);
    dataSet1.setLineWidth(20);
    dataSet1.setCircleSize(10);
    dataSet1.setValueTextSize(15);

    String dataset_label2 = "Company 2";
    ArrayList<Entry> yVals2 = new ArrayList<>();
    yVals2.add(new Entry(80, 0));
    yVals2.add(new Entry(150, 1));
    yVals2.add(new Entry(170, 2));
    yVals2.add(new Entry(200, 3));
    LineDataSet dataSet2 = new LineDataSet(yVals2, dataset_label2);
    dataSet2.setLineWidth(100);
    dataSet2.setCircleSize(10);
    dataSet2.setValueTextSize(15);

    List<LineDataSet> dataSetList = new ArrayList<>();
    dataSetList.add(dataSet1);
    dataSetList.add(dataSet2);

    List<String> xVals = new ArrayList<>();
    xVals.add("Q1");
    xVals.add("Q2");
    xVals.add("Q3");
    xVals.add("Q4");
    LineData data = new LineData(xVals, dataSetList);
    chart.setData(data);
    chart.invalidate();

最後執行折線圖就畫出來了:

如何使用 MPAndroidChart 畫圖,以折線圖為例


以上所述就是小编给大家介绍的《如何使用 MPAndroidChart 畫圖,以折線圖為例》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Art of Computer Programming, Volume 4,  Fascicle 3

The Art of Computer Programming, Volume 4, Fascicle 3

Donald E. Knuth / Addison-Wesley Professional / 2005-08-05 / USD 19.99

Finally, after a wait of more than thirty-five years, the first part of Volume 4 is at last ready for publication. Check out the boxed set that brings together Volumes 1 - 4A in one elegant case, and ......一起来看看 《The Art of Computer Programming, Volume 4, Fascicle 3》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具