安卓案例:使用MPAndroidChart繪製餅狀圖、柱狀圖和折線圖

目錄html

1、MPAndroidChart概述java

2、案例運行效果android

一、主控界面git

二、顯示餅狀圖github

三、顯示柱狀圖app

四、顯示折線圖dom

五、顯示動態折線圖ide

3、項目結構圖佈局

一、Project視圖學習

二、Android視圖

4、實現步驟

一、app的build.gradle裏添加依賴

二、主控界面

(1)佈局activity_main.xml

(2)主界面類MainActivity

三、顯示餅狀圖

(1)佈局activity_pie_chart.xml

(2)餅圖界面類PieChartActivity

四、顯示柱狀圖

(1)佈局activity_bar_chart.xml

(2)柱狀圖界面類BarChartActivity

五、顯示折線圖

(1)佈局activity_line_chart.xml

(2)折線圖界面類LineChartActivity

六、顯示動態折線圖

(1)佈局activity_dynamic_line_chart.xml

(2)動態折線圖界面類DynamicLineChartActivity


1、MPAndroidChart概述

MPAndroidChart是一款優秀的開源圖表插件。

GitHub網址:https://github.com/PhilJay/MPAndroidChart

今天學習三種類型的圖表:餅狀圖、柱狀圖和折線圖

2、案例運行效果

一、主控界面

二、顯示餅狀圖

三、顯示柱狀圖

四、顯示折線圖

五、顯示動態折線圖

3、項目結構圖

一、Project視圖

兩個jar包下載連接:https://pan.baidu.com/s/1quvSQuq-HaCc2vsFJ3IKxw  提取碼:t4rb

二、Android視圖

4、實現步驟

一、app的build.gradle裏添加依賴

二、主控界面

(1)佈局activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="net.hw.mpchart.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="顯示餅狀圖"
        android:onClick="showPieChart"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="顯示柱狀圖"
        android:onClick="showBarChart"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="顯示折線圖"
        android:onClick="showLineChart"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="顯示動態折線圖"
        android:onClick="showDynamicLineChart"/>

</LinearLayout>

(2)主界面類MainActivity

package net.hw.mpchart;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void showPieChart(View view) {
        startActivity(new Intent(MainActivity.this, PieChartActivity.class));
    }

    public void showBarChart(View view) {
        startActivity(new Intent(MainActivity.this, BarChartActivity.class));
    }

    public void showLineChart(View view) {
        startActivity(new Intent(MainActivity.this, LineChartActivity.class));
    }

    public void showDynamicLineChart(View view) {
        startActivity(new Intent(MainActivity.this, DynamicLineChartActivity.class));
    }
}

三、顯示餅狀圖

(1)佈局activity_pie_chart.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.hw.mpchart.PieChartActivity">

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

</LinearLayout>

(2)餅圖界面類PieChartActivity

package net.hw.mpchart;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;

import java.util.ArrayList;

public class PieChartActivity extends AppCompatActivity {

    private PieChart mChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pie_chart);
        mChart = (PieChart) findViewById(R.id.chart);
        showChart(getPieData());
    }

    private void showChart(PieData pieData) {
        mChart.setHoleColorTransparent(true);
        mChart.setHoleRadius(60f);  //內環半徑
        mChart.setTransparentCircleRadius(64f); // 半透明圈半徑
        // mChart.setHoleRadius(0);  // 實心圓
        mChart.setDescription("測試餅狀圖");
        mChart.setDrawCenterText(true);  //餅狀圖中間能夠添加文字
        mChart.setCenterText("2017年季度收入");  //餅狀圖中間的文字
        mChart.setDrawHoleEnabled(true);
        mChart.setRotationAngle(90); // 初始旋轉角度
        mChart.setRotationEnabled(true); // 能夠手動旋轉
        // mChart.setUsePercentValues(true);  //顯示成百分比
        // 設置可觸摸
        mChart.setTouchEnabled(true);
        // 設置數據
        mChart.setData(pieData);

        // 取消高亮顯示
        mChart.highlightValues(null);
        mChart.invalidate();

        Legend mLegend = mChart.getLegend();  //設置比例圖
        mLegend.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);  //最右邊顯示
        mLegend.setForm(Legend.LegendForm.LINE);  //設置比例圖的形狀,默認是方形
        mLegend.setXEntrySpace(7f);
        mLegend.setYEntrySpace(5f);

        //設置動畫
        mChart.animateXY(1000, 1000);
    }

     private PieData getPieData() {
        // xVals用來表示每一個餅塊上的文字
        ArrayList<String> xValues = new ArrayList<String>();

        for (int i = 0; i < 4; i++) {
            xValues.add((i + 1) + "季度");
        }

        // yVals用來表示封裝每一個餅塊的實際數據
        ArrayList<Entry> yValues = new ArrayList<Entry>();

        // 餅圖數據
        float quarterly1 = 456787;
        float quarterly2 = 534283;
        float quarterly3 = 345734;
        float quarterly4 = 658465;

        yValues.add(new Entry(quarterly1, 0));
        yValues.add(new Entry(quarterly2, 1));
        yValues.add(new Entry(quarterly3, 2));
        yValues.add(new Entry(quarterly4, 3));

        // y軸集合
        PieDataSet pieDataSet = new PieDataSet(yValues, "2017年季度收入");
        pieDataSet.setSliceSpace(0f); //設置個餅狀圖之間的距離

        ArrayList<Integer> colors = new ArrayList<Integer>();

        // 餅圖顏色
        colors.add(Color.rgb(205, 205, 205));
        colors.add(Color.rgb(114, 188, 223));
        colors.add(Color.rgb(255, 123, 124));
        colors.add(Color.rgb(57, 135, 200));

        // 設置餅圖顏色
        pieDataSet.setColors(colors);

        // 設置選中態多出的長度
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        float px = 5 * (metrics.densityDpi / 160f);
        pieDataSet.setSelectionShift(px);

        // 建立餅圖數據
        PieData pieData = new PieData(xValues, pieDataSet);

        return pieData;
    }
}

四、顯示柱狀圖

(1)佈局activity_bar_chart.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.hw.mpchart.PieChartActivity">

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

</LinearLayout>

(2)柱狀圖界面類BarChartActivity

package net.hw.mpchart;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;

import java.util.ArrayList;

public class BarChartActivity extends AppCompatActivity {
    private BarChart mChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bar_chart);
        mChart = (BarChart) findViewById(R.id.chart);
        showChart(getBarData());
    }

    /**
     * 顯示柱狀圖表
     *
     * @param barData
     */
    private void showChart(BarData barData) {
        // 設置描述
        mChart.setDescription("測試柱狀圖");
        // 設置可觸摸
        mChart.setTouchEnabled(true);
        // 設置圖表數據
        mChart.setData(barData);
        // 設置動畫
        mChart.animateY(1000);
    }

    /**
     * 獲取柱狀數據
     *
     * @return
     */
    private BarData getBarData() {
        ArrayList<String> xValues = new ArrayList<String>();

        for (int i = 0; i < 4; i++) {
            xValues.add((i + 1) + "季度");
        }

        ArrayList<BarEntry> yValues = new ArrayList<BarEntry>();

        float quarterly1 = 456787;
        float quarterly2 = 534283;
        float quarterly3 = 345734;
        float quarterly4 = 658465;

        yValues.add(new BarEntry(quarterly1, 0));
        yValues.add(new BarEntry(quarterly2, 1));
        yValues.add(new BarEntry(quarterly3, 2));
        yValues.add(new BarEntry(quarterly4, 3));

        BarDataSet barDataSet = new BarDataSet(yValues, "2017年季度收入");

        ArrayList<Integer> colors = new ArrayList<Integer>();

        colors.add(Color.rgb(205, 205, 205));
        colors.add(Color.rgb(114, 188, 223));
        colors.add(Color.rgb(255, 123, 124));
        colors.add(Color.rgb(57, 135, 200));

        barDataSet.setColors(colors);

        BarData barData = new BarData(xValues, barDataSet);

        return barData;
    }
}

五、顯示折線圖

(1)佈局activity_line_chart.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="net.hw.mpchart.PieChartActivity">

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnStart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="doStart"
            android:text="啓動" />

        <Button
            android:id="@+id/btnStop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="doStop"
            android:text="中止" />

    </LinearLayout>

</LinearLayout>

(2)折線圖界面類LineChartActivity

package net.hw.mpchart;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;

public class LineChartActivity extends AppCompatActivity {

    private LineChart mChart;
    private boolean isRunning;
    private Thread thread;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_line_chart);
        mChart = (LineChart) findViewById(R.id.chart);
        showChart(getLineData(12, 2000));

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                mChart.clear(); // 清空圖表
                showChart(getLineData(12, 2000));
            }
        };
    }

    private void showChart(LineData lineData) {
        // 設置描述
        mChart.setDescription("折線圖演示");
        // 設置觸摸模式
        mChart.setTouchEnabled(true);
        // 設置圖表數據
        mChart.setData(lineData);
    }

    /**
     * @param count 橫向點個數
     * @param range 縱向變化幅度
     * @return
     */
    private LineData getLineData(int count, float range) {
        ArrayList<String> xVals = new ArrayList<String>();
        for (int i = 0; i < count; i++) {
            xVals.add((i + 1) + "月");
        }

        /

        ArrayList<Entry> yVals = new ArrayList<Entry>();

        for (int i = 0; i < count; i++) {
            float mult = range / 2f;
            float val = (float) (Math.random() * mult) + 1000;
            yVals.add(new Entry(val, i));
        }

        // 建立數據集
        LineDataSet set = new LineDataSet(yVals, "數據集");
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setColor(ColorTemplate.getHoloBlue());
        set.setCircleColor(Color.YELLOW);
        set.setLineWidth(2f);
        set.setCircleSize(3f);
        set.setFillAlpha(65);
        set.setFillColor(ColorTemplate.getHoloBlue());
        set.setHighLightColor(Color.rgb(244, 117, 117));
        set.setDrawCircleHole(false);

        

        // 建立數據集列表
        ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
        dataSets.add(set);

        // 建立折線數據對象(第二個參數能夠是set)
        LineData lineData = new LineData(xVals, dataSets);
        lineData.setValueTextColor(Color.BLACK);
        lineData.setValueTextSize(9f);

        return lineData;
    }

    public void doStart(View view) {
        isRunning = true;
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRunning) {
                    try {
                        handler.sendEmptyMessage(0x001);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }

    public void doStop(View view) {
        isRunning = false;
        thread = null;
    }
}

六、顯示動態折線圖

(1)佈局activity_dynamic_line_chart.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="net.hw.mpchart.DynamicLineChartActivity" >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="doStart"
        android:text="動態添加數據" />

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

</LinearLayout>

(2)動態折線圖界面類DynamicLineChartActivity

package net.hw.mpchart;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.text.DecimalFormat;

public class DynamicLineChartActivity extends AppCompatActivity {

    // 高溫線下標
    private final int HIGH = 0;
    // 低溫線下標
    private final int LOW = 1;

    private LineChart mChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_line_chart);
        mChart = (LineChart) findViewById(R.id.chart);
        showChart(getLineData());
    }

    /**
     * 顯示圖表
     */
    private void showChart(LineData lineData) {
        // 初始化圖表
        initChart();
        // 數據顯示的顏色
        lineData.setValueTextColor(Color.BLACK);
        // 給圖表設置數據
        mChart.setData(lineData);
    }

    /**
     * 獲取折線數據
     *
     * @return
     */
    private LineData getLineData() {
        // 建立折線數據
        LineData lineData = new LineData();
        // 添加數據集
        lineData.addDataSet(getHighLineDataSet());
        lineData.addDataSet(getLowLineDataSet());
        // 返回折線數據
        return lineData;
    }

    /**
     * 初始化圖表
     */
    private void initChart() {
        // 設置描述
        mChart.setDescription("動態折線圖");
        // 設置可觸摸
        mChart.setTouchEnabled(true);
        // 可拖曳
        mChart.setDragEnabled(true);
        // 可縮放
        mChart.setScaleEnabled(true);
        // 設置繪製網格背景
        mChart.setDrawGridBackground(true);
        mChart.setPinchZoom(true);
        // 設置圖表的背景顏色
        mChart.setBackgroundColor(0xfff5f5f5);
        // 圖表註解(只有當數據集存在時候才生效)
        Legend legend = mChart.getLegend();
        // 設置圖表註解部分的位置
        legend.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
        // 線性,也但是圓
        legend.setForm(Legend.LegendForm.LINE);
        // 顏色
        legend.setTextColor(Color.BLUE);
        // x座標軸
        XAxis xl = mChart.getXAxis();
        xl.setTextColor(0xff00897b);
        xl.setDrawGridLines(false);
        xl.setAvoidFirstLastClipping(true);

        // 幾個x座標軸之間才繪製
        xl.setSpaceBetweenLabels(5);
        // 若是false,那麼x座標軸將不可見
        xl.setEnabled(true);
        // 將X座標軸放置在底部,默認是在頂部。
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);
        // 圖表左邊的y座標軸線
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setTextColor(0xff37474f);
        // 最大值
        leftAxis.setAxisMaxValue(50f);
        // 最小值
        leftAxis.setAxisMinValue(-10f);
        // 不必定要從0開始
        leftAxis.setStartAtZero(false);
        leftAxis.setDrawGridLines(true);
        YAxis rightAxis = mChart.getAxisRight();
        // 不顯示圖表的右邊y座標軸線
        rightAxis.setEnabled(false);
    }


    // 爲高溫線和低溫線添加一個座標點
    private void addChartEntry() {
        // 獲取圖表數據
        LineData lineData = mChart.getData();
        // 添加橫座標值
        lineData.addXValue((lineData.getXValCount()) + "");

        // 增長高溫
        LineDataSet highLineDataSet = lineData.getDataSetByIndex(HIGH);
        float high = (float) ((Math.random()) * 10 + 30);
        Entry entryHigh = new Entry(high, highLineDataSet.getEntryCount());
        lineData.addEntry(entryHigh, HIGH);

        // 增長低溫
        LineDataSet lowLineDataSet = lineData.getDataSetByIndex(LOW);
        float low = (float) ((Math.random()) * 10);
        Entry entryLow = new Entry(low, lowLineDataSet.getEntryCount());
        lineData.addEntry(entryLow, LOW);

        // 使用新數據刷新圖表
        mChart.notifyDataSetChanged();

        // 當前統計圖表中最多在x軸座標線上顯示的總量
        mChart.setVisibleXRangeMaximum(12);

        mChart.moveViewToX(lineData.getXValCount() - 12);
    }

    // 初始化數據集,添加一條高溫統計折線
    private LineDataSet getHighLineDataSet() {
        LineDataSet set = new LineDataSet(null, "高溫");
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        // 折線的顏色
        set.setColor(Color.RED);
        set.setCircleColor(Color.YELLOW);
        set.setLineWidth(2f);
        set.setCircleSize(8f);
        set.setFillAlpha(128);
        set.setCircleColorHole(Color.BLUE);
        set.setHighLightColor(Color.GREEN);
        set.setValueTextColor(Color.RED);
        set.setValueTextSize(10f);
        set.setDrawValues(true);

        set.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex,
                                            ViewPortHandler viewPortHandler) {
                DecimalFormat decimalFormat = new DecimalFormat(".0℃");
                String s = "高溫" + decimalFormat.format(value);
                return s;
            }
        });

        return set;
    }

    // 初始化數據集,添加一條低溫統計折線
    private LineDataSet getLowLineDataSet() {
        LineDataSet set = new LineDataSet(null, "低溫");
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        // 折線的顏色
        set.setColor(ColorTemplate.getHoloBlue());
        set.setCircleColor(Color.BLUE);
        set.setLineWidth(2f);
        set.setCircleSize(8f);
        set.setFillAlpha(128);
        set.setFillColor(ColorTemplate.getHoloBlue());
        set.setHighLightColor(Color.DKGRAY);
        set.setValueTextColor(Color.BLACK);
        set.setCircleColorHole(Color.RED);
        set.setValueTextSize(10f);
        set.setDrawValues(true);

        set.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex,
                                            ViewPortHandler viewPortHandler) {
                DecimalFormat decimalFormat = new DecimalFormat(".0℃");
                String s = "低溫" + decimalFormat.format(value);
                return s;
            }
        });

        return set;
    }

    /**
     * 給圖表添加數據
     *
     * @param view
     */
    public void doStart(View view) {
        addChartEntry();
    }
}

 

本文分享 CSDN - howard2005。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索