美文网首页高级UI
MPAndroidChart,linechart多条折线图自定义

MPAndroidChart,linechart多条折线图自定义

作者: 若非让给给个个 | 来源:发表于2019-11-01 17:04 被阅读0次

    首先来上张图,看一下是不是你要找的功能!


    line_chart_eg.png

    就可以随便加几条折线图,然后底部x轴的数据跟折线图本身并不关联其实。
    下面是详细步骤:
    ps:由于我写的时候我功能已经封装好了,所以封装方法最后会贴出来,但是数据格式比较复杂,不会是你想要的。这里贴的是一个简单未封装的。

    步骤来啦

    第一步:新建一个activity,命名为TestActivity,这个你们应该都会,就不解释了。
    第二步:在项目的gradle中引入MPAndroidChart,并检测是否引入成功。
    implementation 'com.github.gittjy:LoadingDialog:1.0.2'     //对话框
    

    在activity_test.xml中加

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

    然后就运行一下,试试报错没,没报错就代表你的linechart引入成功啦!(不行的话可以联系我)

    第三步:直接复制我下面的就完事了,就可以达到贴图的效果。
    package com.jf.aibei;
    
    import androidx.annotation.Nullable;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.content.ContextCompat;
    
    import android.graphics.Color;
    import android.graphics.DashPathEffect;
    import android.os.Bundle;
    
    import com.github.mikephil.charting.charts.LineChart;
    import com.github.mikephil.charting.components.AxisBase;
    import com.github.mikephil.charting.components.Legend;
    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.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.jf.aibei.bean.LineChartBaseBean;
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    public class LinetestActivity extends AppCompatActivity {
    
    
        LineChart lc;
    
        List<LineChartBaseBean> list;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_linetest);
            lc = findViewById(R.id.chartLine);
            initData();
            initChart();
        }
    
        private void initData() {
            list= new ArrayList<>();
            list.add(new LineChartBaseBean("3/25", 3.8f));
            list.add(new LineChartBaseBean("3/25", 3.8f));
            list.add(new LineChartBaseBean("3/24", 6.8f));
            list.add(new LineChartBaseBean("3/23", 7.8f));
            list.add(new LineChartBaseBean("3/22", 5.4f));
            list.add(new LineChartBaseBean("3/21", 0f));
            list.add(new LineChartBaseBean("3/20", 6f));
            list.add(new LineChartBaseBean("3/19", 9f));
        }
    
        private void initChart() {
            List<Float> m = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                float t = list.get(i).getValue();
                m.add(t);
            }
            List<Entry> entries = new ArrayList<>();
            Float mMin = m.get(0);
            Float mMax = m.get(0);
            for (int i = 0; i < m.size(); i++) {
                if (mMin > m.get(i)) {
                    mMin = m.get(i);
                }
                if (mMax < m.get(i)) {
                    mMax = m.get(i);
                }
                entries.add(new Entry(i, m.get(i)));
            }
            List<Entry> entries2 = new ArrayList<>();
            for (int i = 0; i < 8; i++) {
                float mult = 10;
                float val = (float) (Math.random() * mult);
                entries2.add(new Entry(i, val));
            }
            IAxisValueFormatter formatter = new IAxisValueFormatter() {
                @Override
                public String getFormattedValue(float value, AxisBase axis) {
                    int v = (int) value;
                    if (v <= list.size() && v >= 0) {
                        String st = list.get(v).getKey();
                        String tim1 = "";
                        tim1 = st;
                        return tim1;
                    } else {
                        return null;
                    }
                }
            };
            lc.setTouchEnabled(true);//可接触
            lc.setDragEnabled(false);//可拖拽
            lc.setScaleEnabled(false);//可缩放
            lc.setDoubleTapToZoomEnabled(false);
            lc.setScaleYEnabled(false);
            lc.setDrawGridBackground(false);//画网格背景
            lc.setDrawBorders(false);  //是否在折线图上添加边框
            lc.setPinchZoom(false);//设置少量移动
    
    
            //图表注解
            lc.getLegend().setEnabled(false);
            lc.getDescription().setEnabled(false);
    
            //x轴坐标
            XAxis xAxis = lc.getXAxis();
            xAxis.setTextColor(Color.BLACK);//x轴文字颜色
            xAxis.setTextSize(12f);
    
            xAxis.setEnabled(true);//显示x轴
            xAxis.setGridLineWidth(0f);
            xAxis.setLabelCount(7, false);
            xAxis.setDrawAxisLine(true);//是否绘制轴线
            xAxis.setDrawGridLines(true);//设置x轴上每个点对应的线
            xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
            xAxis.setGranularity(1);
            xAxis.setGridLineWidth(0.5f);
            xAxis.setGridColor(Color.parseColor("#9E9E9E"));
            xAxis.setValueFormatter(formatter);
            LimitLine ll2 = new LimitLine(8f, "");
            ll2.setLineWidth(3f);
            ll2.setLineColor(ContextCompat.getColor(this, android.R.color.black));
            ll2.enableDashedLine(5f, 5f, 0f);//虚线
            ll2.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);//设置标签显示的位置
            ll2.setTextColor(ContextCompat.getColor(this, android.R.color.background_dark));
            ll2.setTextSize(10f);
            
            //Y轴坐标
            YAxis yAxis = lc.getAxisLeft();
            yAxis.setAxisMinValue(0);
            yAxis.setAxisMaxValue(12f);
            yAxis.setDrawGridLines(false);//取消网格线
            yAxis.setEnabled(true);//不显示Y轴
            yAxis.addLimitLine(ll2);
            yAxis.setLabelCount(7, true);
            lc.getAxisRight().setEnabled(false);//不显示右侧
            LineDataSet lineDataSet = new LineDataSet(entries, "aaaa");
            LineDataSet lineDataSet2 = new LineDataSet(entries2, "bbbb");
    
    
    
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);//设置折线图的显示模式,可以自行设置上面的值进行查看不同之处
            lineDataSet.setColor(ContextCompat.getColor(this, android.R.color.holo_blue_light));//设置线的颜色
            lineDataSet.setLineWidth(1.5f);//设置线的宽度
            lineDataSet.setCircleColor(ContextCompat.getColor(this, android.R.color.holo_blue_light));//设置圆圈的颜色
            lineDataSet.setCircleColorHole(ContextCompat.getColor(this, android.R.color.holo_blue_light));//设置圆圈内部洞的颜色
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);//设置线数据依赖于左侧y轴
            lineDataSet.setDrawFilled(true);//设置不画数据覆盖的阴影层
            lineDataSet.setDrawValues(true);//不绘制线的数据
            lineDataSet.setValueTextSize(15f);//如果不绘制线的数据 这句代码也不用设置了
            lineDataSet.enableDashedHighlightLine(10f, 5f, 0f);//没看出来效果
            lineDataSet.setFormLineWidth(10f);//只有lineDataSet.setForm(Legend.LegendForm.LINE);时才有作用 这里我们设置的是圆所以这句代码直接注释
            lineDataSet.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));//设置虚线,只有lineDataSet.setForm(Legend.LegendForm.LINE);时才有作用
            lineDataSet.setCircleRadius(4f);//设置每个折线点的大小
            lineDataSet.setFormSize(15.f);//设置当前这条线的图例的大小
            lineDataSet.setForm(Legend.LegendForm.LINE);//设置图例显示为线
            
            LineData data = new LineData(lineDataSet,lineDataSet2);//创建图表数据源
            lc.setData(data);//设置图表数据
    
        }
    }
    

    贴进去就可以运行啦。(这个是测试用的,里面每个参数的作用不是写的很全。下面我贴我封装好的)。案例可以到这里就结束啦。

    我是神奇的分隔线-------------------啦啦啦
    下面就是实际封装的啦
    LearningEmotionBean是后台回传的数据,跟linechart要使用的不完全符合,要做调整,你们可以根据自己情况适当调整。

    package com.jf.aibei.tools;
    
    import android.graphics.Color;
    import android.graphics.Typeface;
    
    import com.github.mikephil.charting.charts.LineChart;
    import com.github.mikephil.charting.components.AxisBase;
    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.IAxisValueFormatter;
    import com.jf.aibei.bean.LearningEmotionBean;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class MLineChart {
    
        private LearningEmotionBean learnEmotion;
        private LineChart mLineChart;
    
        public MLineChart(LearningEmotionBean learnEmotion, LineChart mLineChart) {
            this.learnEmotion = learnEmotion;
            this.mLineChart = mLineChart;
        }
    
    
        /**
         * 将类接收的linechart进行样式调整并回传
         * @return mLineChart
         */
        public LineChart getLineChart(){
            mLineChart.setBackgroundColor(Color.parseColor("#EDF3F3"));//设置整个lienchart的背景颜色
            //设置折线本身样式
            mLineChart.getDescription().setEnabled(false);//设置折线图的描述,一般不需要
            mLineChart.setTouchEnabled(true);//设置是否能点击
            mLineChart.setDragEnabled(true);//设置是否可以拖拽
            mLineChart.setDragDecelerationEnabled(false);//设置手拖拽放开后图是否继续滚动
            mLineChart.setDragDecelerationFrictionCoef(0.9f);//设置继续滚动的速度
            mLineChart.setScaleEnabled(true);//设置是否可以缩放
            mLineChart.setDrawGridBackground(false);//设置图表的背景颜色
            mLineChart.setHighlightPerDragEnabled(true);//能否拖拽高亮线(数据点与坐标的提示线),默认是true
            mLineChart.setPinchZoom(true);//设置是否能扩大缩小
    
            //设置折线图标签样式
            Legend l = mLineChart.getLegend();//legend是设置折线图的标签的样式,不是设置折线图本身
            l.setForm(Legend.LegendForm.CIRCLE);//设置标签样式为圆形
            l.setTypeface(Typeface.DEFAULT_BOLD);//设置使用何种字体
            l.setTextSize(11f);//设置字体尺寸
            l.setTextColor(Color.WHITE);//设置字体颜色
            l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);//设置标签上下位置
            l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);//设置标签左右位置
            l.setOrientation(Legend.LegendOrientation.HORIZONTAL);//设置标签排布方式
            l.setDrawInside(false);
    
            //设置x和y轴的样式
            YAxis rightAxis = mLineChart.getAxisRight();
            rightAxis.setEnabled(false);
                //设置图表左边的y轴禁用
            YAxis leftAxis = mLineChart.getAxisLeft();
            leftAxis.setEnabled(false);
                //设置x轴
            XAxis xAxis = mLineChart.getXAxis();
            xAxis.setTextColor(Color.parseColor("#333333"));
            xAxis.setTextSize(11f);
            xAxis.setAxisMinimum(0f);
            xAxis.setDrawAxisLine(true);//是否绘制轴线
            xAxis.setDrawGridLines(true);//设置x轴上每个点对应的线
            xAxis.setDrawLabels(true);//绘制标签  是否显示x轴的标签尺度
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
            xAxis.setGranularity(1f);//禁止放大后x轴标签重绘
    
            //设置x轴的值
            xAxis.setGranularity(1f);//缩放的时候有用,比如放大的时候,我不想把横轴的月份再细分
            IAxisValueFormatter formatter = new IAxisValueFormatter() {
                @Override
                public String getFormattedValue(float value, AxisBase axis) {
                    //设置 xAxis.setGranularity(1);后 value是从0开始的,每次加1,
                    List<String> xAxisList = getXaxisList();
                    int v = (int) value;
                    if (v <= xAxisList.size() && v >= 0) {
                        String st = xAxisList.get(v);
                        return st;
                    } else {
                        return null;
                    }
                }
            };
            xAxis.setValueFormatter(formatter);
            return mLineChart;
        }
    
    
        /**
         * 为设置x轴的日期,生成对应格式的数据
         * @param
         * @return mXaxisList
         */
        private List<String> getXaxisList(){
            List<String> mXaxisList = new ArrayList<>();
            for (int i=0;i<learnEmotion.getXaxis().getData().size();i++){
                mXaxisList.add(learnEmotion.getXaxis().getData().get(i));
            }
            return mXaxisList;
        }
    
    
        /**
         * 返回linechart所需要的格式的数据,将后端传回的数据进行格式转换
         * @return mLineData
         */
        public LineData getData(){
    
            ArrayList<Entry> poetryList = new ArrayList<Entry>();
            for (int i=0;i<learnEmotion.getSeries().get(0).getData().size();i++){
                poetryList.add(new Entry(i,Float.valueOf(learnEmotion.getSeries().get(0).getData().get(i))));
            }
    
            ArrayList<Entry> articleList = new ArrayList<Entry>();
            for (int i=0;i<learnEmotion.getSeries().get(1).getData().size();i++){
                articleList.add(new Entry(i,Float.valueOf(learnEmotion.getSeries().get(1).getData().get(i))));
            }
    
            ArrayList<Entry> sentenceList = new ArrayList<Entry>();
            for (int i=0;i<learnEmotion.getSeries().get(2).getData().size();i++){
                sentenceList.add(new Entry(i,Float.valueOf(learnEmotion.getSeries().get(2).getData().get(i))));
            }
    
            LineDataSet poetryData, articleData, sentenceData;
    
            poetryData = new LineDataSet(poetryList, "aa");
            articleData = new LineDataSet(articleList, "bb");
            sentenceData = new LineDataSet(sentenceList, "cc");
    
            LineData mLineData = new LineData(poetryData, articleData, sentenceData);
    
            return mLineData;
        }
    
    
    }
    

    最后再贴上如何使用

    MLineChart mLineChart = new MLineChart(learnTrack.getData(),lineChart);
            LineChart lineChart = mLineChart.getLineChart();
            LineData lineData = mLineChart.getData();
            lineChart.setData(lineData);
    

    这里传给mLineChart的第二个参数lineChart就是你layout样式文件里面的linechart,其他好像也没好多要说的了。有不懂的可以联系我呀

    告辞!

    相关文章

      网友评论

        本文标题:MPAndroidChart,linechart多条折线图自定义

        本文链接:https://www.haomeiwen.com/subject/zyfqbctx.html