AndroidMPChart学习之LineChart详细总结

来源:互联网 发布:大数据技术与城市规划 编辑:程序博客网 时间:2024/05/21 18:49

AndroidMPChart之LineChart详细总结

由于项目需求,所以对GitHub上的AndroidMPChart中的LineChart进行了研究,总结下方便自己下次使用,同时也可以方便他人学习使用:

先看效果图如下:


一:添加依赖:

1.1在项目的module中的build.gradle添加如下代码:

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

1.2 在依赖中添加如下代码依赖:

 compile 'com.github.PhilJay:MPAndroidChart:v3.0.2'

二:使用

2.1 首先定义好自己的布局:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <com.github.mikephil.charting.charts.LineChart        android:id="@+id/chart1"        android:layout_width="match_parent"        android:layout_height="match_parent" /></RelativeLayout>

2.2 在代码中找控件:

 mChart = (LineChart) findViewById(R.id.chart1);

2.3 设置LineChart的基本属性:

 //此属性设置之后,点击图标中的某个点网格会自动将此点移动到屏幕中心 不设置则没反应        mChart.setOnChartValueSelectedListener(this);        // no description text        // mChart.getDescription().setEnabled(false);        //设置是否绘制chart边框的线        mChart.setDrawBorders(false);        //设置chart边框线颜色        mChart.setBorderColor(Color.RED);        //设置chart边框线宽度        mChart.setBorderWidth(1f);        //设置chart是否可以触摸        mChart.setTouchEnabled(true);        mChart.setDragDecelerationFrictionCoef(0.9f);        //设置是否可以拖拽        mChart.setDragEnabled(true);        //设置是否可以缩放 x和y,默认true        mChart.setScaleEnabled(true);        //设置是否可以通过双击屏幕放大图表。默认是true        mChart.setDoubleTapToZoomEnabled(false);        //是否启用网格背景        mChart.setDrawGridBackground(false);        mChart.setHighlightPerDragEnabled(true);        //设置chart动画 x轴y轴都有动画        //mChart.animateXY(2000, 2000);        // false代表缩放时X与Y轴分开缩放,true代表同时缩放        mChart.setPinchZoom(true);        // set an alternative background color        //图表背景颜色的设置        mChart.setBackgroundColor(Color.LTGRAY);        //图表进入的动画时间        mChart.animateX(2500);        //描述信息        Description description = new Description();        description.setText("描述信息相关内容");        //设置描述信息        mChart.setDescription(description);        //设置没有数据时显示的文本        mChart.setNoDataText("没有数据撒...")

2.4 表头Legend:

  Legend l = mChart.getLegend();        // modify the legend ...        //表头代表线条说明前的图形 可以设置线形,圆形,方形        l.setForm(LegendForm.SQUARE);        l.setTypeface(mTfLight);        //表头字体大小        l.setTextSize(11f);        //表头线条说明的颜色        l.setTextColor(Color.RED);        //表头线条放置的位置        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);        //表头多条线条的排列方式        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);        //表头的说明是否绘制到图表内部        l.setDrawInside(false);

2.5 X轴数据设置:

   xAxis = mChart.getXAxis();        xAxis.setTypeface(mTfLight);        xAxis.setTextSize(8f);        //X轴显示的位置        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM_INSIDE);        //X轴        xAxis.setSpaceMin(0.5f);        //X轴数据的颜色        xAxis.setTextColor(Color.BLUE);        //是否绘制X轴的网格线        xAxis.setDrawGridLines(false);        xAxis.setDrawAxisLine(false);        //TODO 设置x轴坐标显示的数量  加true才能显示设置的数量 一旦加true后续的x轴数据显示有问题,        // xAxis.setLabelCount(5,true);        xAxis.setLabelCount(5);        //设置竖线为虚线样子        xAxis.enableGridDashedLine(10f, 10f, 0f);        //图表第一个和最后一个label数据不超出左边和右边的Y轴        // xAxis.setAvoidFirstLastClipping(true);        /********************************************************************************/        final Map<Integer, String> xMap = new HashMap<>();        final String[] valueArry = {"2017-05-11", "2017-05-12", "2017-05-13", "2017-05-14", "2017-05-15","2017-05-16", "2017-05-17", "2017-35-18", "2017-05-19", "2017-05-20","2017-05-21", "2017-05-22", "2017-05-23", "2017-05-24", "2017-05-25","2017-05-26", "2017-05-27", "2017-05-28", "2017-05-29", "2017-05-30"};        for (int i = 0; i < yVals1.size(); i++) {           xMap.put((int) yVals1.get(i).getX(), valueArry[i]);        }        //自定义x轴标签数据        xAxis.setValueFormatter(new IAxisValueFormatter() {            @Override            public String getFormattedValue(float value, AxisBase axis) {                return xMap.get((int)value);            }        });        /********************************************************************************/

2.6 设置限制线:

        //设置限制线 70代表某个该轴某个值,也就是要画到该轴某个值上        LimitLine limitLine = new LimitLine(70);        //设置限制线的宽        limitLine.setLineWidth(1f);        //设置限制线的颜色        limitLine.setLineColor(Color.RED);        //设置基线的位置        limitLine.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_TOP);        limitLine.setLabel("我是基线,也可以叫我水位线");        //设置限制线为虚线        limitLine.enableDashedLine(10f, 10f, 0f);

2.7 Y轴属性设置:

//左侧Y轴属性设置        YAxis leftAxis = mChart.getAxisLeft();        leftAxis.setTypeface(mTfLight);        //Y轴数据的字体颜色        leftAxis.setTextColor(ColorTemplate.getHoloBlue());        //左侧Y轴最大值        leftAxis.setAxisMaximum(200f);        //左侧Y轴最小值        leftAxis.setAxisMinimum(0f);        //是否绘制Y轴网格线        leftAxis.setDrawGridLines(false);        //TODO 什么属性?        leftAxis.setGranularityEnabled(true);        //左边Y轴添加限制线        leftAxis.addLimitLine(limitLine);        //右侧Y轴坐标        YAxis rightAxis = mChart.getAxisRight();        rightAxis.setTypeface(mTfLight);        rightAxis.setTextColor(Color.WHITE);        rightAxis.setAxisMaximum(900);        rightAxis.setAxisMinimum(0);        rightAxis.setDrawGridLines(false);        //是否绘制等0线        rightAxis.setDrawZeroLine(true);        rightAxis.setGranularityEnabled(false);

2.8 设置数据setData():

private void setData(int count, float range) {        yVals1 = new ArrayList<>();        for (int i = 0; i < count; i++) {            float mult = range / 2f;            float val = (float) (Math.random() * mult) + 50;            yVals1.add(new Entry(i, val));        }        ArrayList<Entry> yVals2 = new ArrayList<Entry>();        for (int i = 0; i < count; i++) {            float mult = range;            float val = (float) (Math.random() * mult) + 450;            yVals2.add(new Entry(i, val));//            if(i == 10) {//                yVals2.add(new Entry(i, val + 50));//            }        }        ArrayList<Entry> yVals3 = new ArrayList<>();        for (int i = 0; i < count; i++) {            float mult = range;            float val = (float) (Math.random() * mult) + 500;            yVals3.add(new Entry(i, val));        }        LineDataSet set1, set2, set3;        if (mChart.getData() != null &&                mChart.getData().getDataSetCount() > 0) {            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);            set2 = (LineDataSet) mChart.getData().getDataSetByIndex(1);            set3 = (LineDataSet) mChart.getData().getDataSetByIndex(2);            set1.setValues(yVals1);            set2.setValues(yVals2);            set3.setValues(yVals3);            mChart.getData().notifyDataChanged();            mChart.notifyDataSetChanged();        } else {            // create a dataset and give it a type            set1 = new LineDataSet(yVals1, "数据1");            set1.setCubicIntensity(1.0f);            //数据对应的是左边还是右边的Y值            set1.setAxisDependency(AxisDependency.LEFT);            //线条的颜色            set1.setColor(Color.WHITE);            //表中数据圆点的颜色            set1.setCircleColor(Color.RED);            //表中数据线条的宽度            set1.setLineWidth(2f);            //表中数据圆点的半径            set1.setCircleRadius(3f);            //设置线面部分是否填充            set1.setDrawFilled(false);            //填充的颜色透明度            set1.setFillAlpha(255);            //填充颜色            set1.setFillColor(ColorTemplate.rgb("ffffff"));            set1.setHighLightColor(Color.rgb(244, 117, 117));            //绘制的数据的圆点是否是实心还是空心            set1.setDrawCircleHole(false);            //set1.setFillFormatter(new MyFillFormatter(0f));            //set1.setDrawHorizontalHighlightIndicator(false);            //set1.setVisible(false);            //set1.setCircleHoleColor(Color.WHITE);            // create a dataset and give it a type            set2 = new LineDataSet(yVals2, "数据2");            set2.setAxisDependency(AxisDependency.RIGHT);            set2.setColor(Color.RED);            set2.setCircleColor(Color.WHITE);            set2.setLineWidth(2f);            set2.setCircleRadius(3f);            set2.setFillAlpha(65);            set2.setFillColor(Color.RED);            set2.setDrawCircleHole(false);            set2.setHighLightColor(Color.rgb(244, 117, 117));            //set2.setFillFormatter(new MyFillFormatter(900f));            set3 = new LineDataSet(yVals3, "数据3");            set3.setAxisDependency(AxisDependency.RIGHT);            set3.setColor(Color.YELLOW);            set3.setCircleColor(Color.WHITE);            set3.setLineWidth(2f);            set3.setCircleRadius(3f);            set3.setFillAlpha(65);            set3.setFillColor(ColorTemplate.colorWithAlpha(Color.YELLOW, 200));            set3.setDrawCircleHole(false);            set3.setHighLightColor(Color.rgb(244, 117, 117));            LineDataSet set4 = new LineDataSet(yVals1, "Content");//            LineData lineData = new LineData(xVals, set1);            // create a data object with the datasets            LineData data = new LineData(set1, set2, set3);            //设置图标中显示数字的颜色            data.setValueTextColor(Color.RED);            //设置图标中显示数字的大小            data.setValueTextSize(9f);            // set data            mChart.setData(data);        }    }

三 最后附上全部代码:


import android.graphics.Color;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.WindowManager;import com.github.mikephil.charting.charts.LineChart;import com.github.mikephil.charting.components.AxisBase;import com.github.mikephil.charting.components.Description;import com.github.mikephil.charting.components.Legend;import com.github.mikephil.charting.components.Legend.LegendForm;import com.github.mikephil.charting.components.LimitLine;import com.github.mikephil.charting.components.XAxis;import com.github.mikephil.charting.components.YAxis;import com.github.mikephil.charting.components.YAxis.AxisDependency;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.IAxisValueFormatter;import com.github.mikephil.charting.highlight.Highlight;import com.github.mikephil.charting.listener.OnChartValueSelectedListener;import com.github.mikephil.charting.utils.ColorTemplate;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;public class LineChartActivity2 extends DemoBase implements        OnChartValueSelectedListener {    private LineChart mChart;    private ArrayList<Entry> yVals1;    private XAxis xAxis;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,                WindowManager.LayoutParams.FLAG_FULLSCREEN);        setContentView(R.layout.activity_linechart);        mChart = (LineChart) findViewById(R.id.chart1);        //此属性设置之后,点击图标中的某个点网格会自动将此点移动到屏幕中心 不设置则没反应        mChart.setOnChartValueSelectedListener(this);        // no description text//        mChart.getDescription().setEnabled(false);        //设置是否绘制chart边框的线        mChart.setDrawBorders(false);        //设置chart边框线颜色        mChart.setBorderColor(Color.RED);        //设置chart边框线宽度        mChart.setBorderWidth(1f);        //设置chart是否可以触摸        mChart.setTouchEnabled(true);        mChart.setDragDecelerationFrictionCoef(0.9f);        // //设置是否可以拖拽        mChart.setDragEnabled(true);//        设置是否可以缩放 x和y,默认true        mChart.setScaleEnabled(true);        //设置是否可以通过双击屏幕放大图表。默认是true        mChart.setDoubleTapToZoomEnabled(false);        //是否启用网格背景        mChart.setDrawGridBackground(false);        mChart.setHighlightPerDragEnabled(true);        //设置chart动画 x轴y轴都有动画//        mChart.animateXY(2000, 2000);        // false代表缩放时X与Y轴分开缩放,true代表同时缩放        mChart.setPinchZoom(true);        // set an alternative background color        //图表背景颜色的设置        mChart.setBackgroundColor(Color.LTGRAY);        //图表进入的动画时间        mChart.animateX(2500);        // add data        setData(20, 30);        //描述信息        Description description = new Description();        description.setText("描述信息相关内容");        //设置描述信息        mChart.setDescription(description);        //设置没有数据时显示的文本        mChart.setNoDataText("没有数据撒...");        // get the legend (only possible after setting data)        Legend l = mChart.getLegend();        // modify the legend ...        //表头代表线条说明前的图形 可以设置线形,圆形,方形        l.setForm(LegendForm.SQUARE);        l.setTypeface(mTfLight);        //表头字体大小        l.setTextSize(11f);        //表头线条说明的颜色        l.setTextColor(Color.RED);        //表头线条放置的位置        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);        //表头多条线条的排列方式        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);        //表头的说明是否绘制到图表内部        l.setDrawInside(false);//        l.setYOffset(11f);        xAxis = mChart.getXAxis();        xAxis.setTypeface(mTfLight);        xAxis.setTextSize(8f);        //X轴显示的位置        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM_INSIDE);        //X轴        xAxis.setSpaceMin(0.5f);        //X轴数据的颜色        xAxis.setTextColor(Color.BLUE);        //是否绘制X轴的网格线        xAxis.setDrawGridLines(false);        xAxis.setDrawAxisLine(false);        //TODO 设置x轴坐标显示的数量  加true才能显示设置的数量 一旦加true后续的x轴数据显示有问题,        // xAxis.setLabelCount(5,true);        xAxis.setLabelCount(5);        //设置竖线为虚线样子        xAxis.enableGridDashedLine(10f, 10f, 0f);        /********************************************************************************/        //图表第一个和最后一个label数据不超出左边和右边的Y轴        // xAxis.setAvoidFirstLastClipping(true);        //设置限制线 70代表某个该轴某个值,也就是要画到该轴某个值上        LimitLine limitLine = new LimitLine(70);        //设置限制线的宽        limitLine.setLineWidth(1f);        //设置限制线的颜色        limitLine.setLineColor(Color.RED);        //设置基线的位置        limitLine.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_TOP);        limitLine.setLabel("我是基线,也可以叫我水位线");        //设置限制线为虚线        limitLine.enableDashedLine(10f, 10f, 0f);        /********************************************************************************/        final Map<Integer, String> xMap = new HashMap<>();        final String[] valueArry = {"2017-05-11", "2017-05-12", "2017-05-13", "2017-05-14", "2017-05-15","2017-05-16", "2017-05-17", "2017-35-18", "2017-05-19", "2017-05-20","2017-05-21", "2017-05-22", "2017-05-23", "2017-05-24", "2017-05-25","2017-05-26", "2017-05-27", "2017-05-28", "2017-05-29", "2017-05-30"};        for (int i = 0; i < yVals1.size(); i++) {           xMap.put((int) yVals1.get(i).getX(), valueArry[i]);        }        //自定义x轴标签数据        xAxis.setValueFormatter(new IAxisValueFormatter() {            @Override            public String getFormattedValue(float value, AxisBase axis) {                return xMap.get((int)value);            }        });        /********************************************************************************/        //左侧Y轴属性设置        YAxis leftAxis = mChart.getAxisLeft();        leftAxis.setTypeface(mTfLight);        //Y轴数据的字体颜色        leftAxis.setTextColor(ColorTemplate.getHoloBlue());        //左侧Y轴最大值        leftAxis.setAxisMaximum(200f);        //左侧Y轴最小值        leftAxis.setAxisMinimum(0f);        //是否绘制Y轴网格线        leftAxis.setDrawGridLines(false);        //TODO 什么属性?        leftAxis.setGranularityEnabled(true);        //左边Y轴添加限制线        leftAxis.addLimitLine(limitLine);        //右侧Y轴坐标        YAxis rightAxis = mChart.getAxisRight();        rightAxis.setTypeface(mTfLight);        rightAxis.setTextColor(Color.WHITE);        rightAxis.setAxisMaximum(900);        rightAxis.setAxisMinimum(0);        rightAxis.setDrawGridLines(false);        //是否绘制等0线        rightAxis.setDrawZeroLine(true);        rightAxis.setGranularityEnabled(false);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.line, menu);        return true;    }    private void setData(int count, float range) {        yVals1 = new ArrayList<>();        for (int i = 0; i < count; i++) {            float mult = range / 2f;            float val = (float) (Math.random() * mult) + 50;            yVals1.add(new Entry(i, val));        }        ArrayList<Entry> yVals2 = new ArrayList<Entry>();        for (int i = 0; i < count; i++) {            float mult = range;            float val = (float) (Math.random() * mult) + 450;            yVals2.add(new Entry(i, val));//            if(i == 10) {//                yVals2.add(new Entry(i, val + 50));//            }        }        ArrayList<Entry> yVals3 = new ArrayList<>();        for (int i = 0; i < count; i++) {            float mult = range;            float val = (float) (Math.random() * mult) + 500;            yVals3.add(new Entry(i, val));        }        LineDataSet set1, set2, set3;        if (mChart.getData() != null &&                mChart.getData().getDataSetCount() > 0) {            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);            set2 = (LineDataSet) mChart.getData().getDataSetByIndex(1);            set3 = (LineDataSet) mChart.getData().getDataSetByIndex(2);            set1.setValues(yVals1);            set2.setValues(yVals2);            set3.setValues(yVals3);            mChart.getData().notifyDataChanged();            mChart.notifyDataSetChanged();        } else {            // create a dataset and give it a type            set1 = new LineDataSet(yVals1, "数据1");            set1.setCubicIntensity(1.0f);            //数据对应的是左边还是右边的Y值            set1.setAxisDependency(AxisDependency.LEFT);            //线条的颜色            set1.setColor(Color.WHITE);            //表中数据圆点的颜色            set1.setCircleColor(Color.RED);            //表中数据线条的宽度            set1.setLineWidth(2f);            //表中数据圆点的半径            set1.setCircleRadius(3f);            //设置线面部分是否填充            set1.setDrawFilled(false);            //填充的颜色透明度            set1.setFillAlpha(255);            //填充颜色            set1.setFillColor(ColorTemplate.rgb("ffffff"));            set1.setHighLightColor(Color.rgb(244, 117, 117));            //绘制的数据的圆点是否是实心还是空心            set1.setDrawCircleHole(false);            //set1.setFillFormatter(new MyFillFormatter(0f));            //set1.setDrawHorizontalHighlightIndicator(false);            //set1.setVisible(false);            //set1.setCircleHoleColor(Color.WHITE);            // create a dataset and give it a type            set2 = new LineDataSet(yVals2, "数据2");            set2.setAxisDependency(AxisDependency.RIGHT);            set2.setColor(Color.RED);            set2.setCircleColor(Color.WHITE);            set2.setLineWidth(2f);            set2.setCircleRadius(3f);            set2.setFillAlpha(65);            set2.setFillColor(Color.RED);            set2.setDrawCircleHole(false);            set2.setHighLightColor(Color.rgb(244, 117, 117));            //set2.setFillFormatter(new MyFillFormatter(900f));            set3 = new LineDataSet(yVals3, "数据3");            set3.setAxisDependency(AxisDependency.RIGHT);            set3.setColor(Color.YELLOW);            set3.setCircleColor(Color.WHITE);            set3.setLineWidth(2f);            set3.setCircleRadius(3f);            set3.setFillAlpha(65);            set3.setFillColor(ColorTemplate.colorWithAlpha(Color.YELLOW, 200));            set3.setDrawCircleHole(false);            set3.setHighLightColor(Color.rgb(244, 117, 117));            LineDataSet set4 = new LineDataSet(yVals1, "Content");//            LineData lineData = new LineData(xVals, set1);            // create a data object with the datasets            LineData data = new LineData(set1, set2, set3);            //设置图标中显示数字的颜色            data.setValueTextColor(Color.RED);            //设置图标中显示数字的大小            data.setValueTextSize(9f);            // set data            mChart.setData(data);        }    }    @Override    public void onValueSelected(Entry e, Highlight h) {        Log.i("Entry selected", e.toString());        mChart.centerViewToAnimated(e.getX(), e.getY(), mChart.getData().getDataSetByIndex(h.getDataSetIndex())                .getAxisDependency(), 500);        //mChart.zoomAndCenterAnimated(2.5f, 2.5f, e.getX(), e.getY(), mChart.getData().getDataSetByIndex(dataSetIndex)        // .getAxisDependency(), 1000);        //mChart.zoomAndCenterAnimated(1.8f, 1.8f, e.getX(), e.getY(), mChart.getData().getDataSetByIndex(dataSetIndex)        // .getAxisDependency(), 1000);    }    @Override    public void onNothingSelected() {        Log.i("Nothing selected", "Nothing selected.");    }//    @Override//    public void onStartTrackingTouch(SeekBar seekBar) {//        // TODO Auto-generated method stub////    }////    @Override//    public void onStopTrackingTouch(SeekBar seekBar) {//        // TODO Auto-generated method stub////    }}


3.1基类DemoBase,这个是原项目的基类:

import android.graphics.Typeface;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.FragmentActivity;/** * Baseclass of all Activities of the Demo Application. *  * @author Philipp Jahoda */public abstract class DemoBase extends FragmentActivity {    protected String[] mMonths = new String[] {            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"    };    protected String[] mParties = new 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"    };    protected Typeface mTfRegular;    protected Typeface mTfLight;    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        mTfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");        mTfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf");    }    protected float getRandom(float range, float startsfrom) {        return (float) (Math.random() * range) + startsfrom;    }    @Override    public void onBackPressed() {        super.onBackPressed();        overridePendingTransition(R.anim.move_left_in_activity, R.anim.move_right_out_activity);    }}

原创粉丝点击