MPAndroidChart,linechart多条折线图自定义X轴,封装方法,详细解析

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


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,其他好像也没好多要说的了。有不懂的可以联系我呀

告辞!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,084评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,623评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,450评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,322评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,370评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,274评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,126评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,980评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,414评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,599评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,773评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,470评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,080评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,713评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,852评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,865评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,689评论 2 354

推荐阅读更多精彩内容