Android柱状图MPAndroidChart使用

MPAndroidChart在github上地址:https://github.com/PhilJay/MPAndroidChart

依赖:

Project 的build.gradle文件中添加

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}
然后在 module中的build,gradle 中添加

dependencies {
    implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
}

原博客连接

https://blog.csdn.net/ww897532167/article/details/74171294#3.1%20%E5%8E%BB%E6%8E%89%E5%9B%BE%E8%A1%A8%E5%A4%96%E6%A1%86%EF%BC%8C%E6%8F%8F%E8%BF%B0%E5%86%85%E5%AE%B9%E4%BB%A5%E5%8F%8AX%20Y%E8%BD%B4%E7%BA%BF%E6%9D%A1

稍微简化一点之后

使用流程如下

  • 得到BarChart对象 并初始化
  • 得到BarEntry对象,此处添加(X,Y)值
  • 得到BarDataSet对象,添加BarEntry对象
  • 得到BarData对象,添加BarDaraSet对象
  • 显示柱状图 BarChart.setData(BarData)

初始化设置

   /***图表设置***/
        //背景颜色
        barChart.setBackgroundColor(Color.WHITE);
        //不显示图表网格
        barChart.setDrawGridBackground(false);
        //背景阴影
        barChart.setDrawBarShadow(false);
        barChart.setHighlightFullBarEnabled(false);
        //显示边框
        barChart.setDrawBorders(true);
        //设置动画效果
//        barChart.animateY(1000,);
//        barChart.animateX(1000,);

        /***XY轴的设置***/
        //X轴设置显示位置在底部
        xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//        xAxis.setAxisMinimum(0f);
//        xAxis.setGranularity(1f);

        leftAxis = barChart.getAxisLeft();
        rightAxis = barChart.getAxisRight();
        //保证Y轴从0开始,不然会上移一点
//        leftAxis.setAxisMinimum(0f);
//        rightAxis.setAxisMinimum(0f);

        /***折线图例 标签 设置***/
        legend = barChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(11f);
        //显示位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);


        //不显示表边框
        barChart.setDrawBorders(false);
//        不显示右下角描述内容
        Description description = new Description();
        description.setEnabled(false);
        barChart.setDescription(description);
//        不显示X轴 Y轴线条
        xAxis.setDrawAxisLine(false);
        leftAxis.setDrawAxisLine(false);
        rightAxis.setDrawAxisLine(false);
        leftAxis.setEnabled(false);

显示单行柱状图


    public void showBarChart(List<Integer> dateValueList, String name, int color) {
        ArrayList<BarEntry> entries = new ArrayList<>();
        for (int i = 0; i < dateValueList.size(); i++) {
            /**
             * 此处还可传入Drawable对象 BarEntry(float x, float y, Drawable icon)
             * 即可设置柱状图顶部的 icon展示
             */
            BarEntry barEntry = new BarEntry(i, (float) dateValueList.get(i));
            entries.add(barEntry);
        }
        // 每一个BarDataSet代表一类柱状图
        BarDataSet barDataSet = new BarDataSet(entries, name);
        initBarDataSet(barDataSet, color);

        BarData data = new BarData(barDataSet);
        barChart.setData(data);
    }

调用方法:

    for (int i = 1; i < 10; i++) {
            listData.add(i+10);
            listData2.add(i+15);

        }
        initBarChart();
        showBarChart(listData,"名称",getResources().getColor(R.color.blue));
}

效果为

 柱状图外观完善

上图与需要实现的效果差距还是挺大的,下面待改善的点,然后挨着就行修改

  • 去掉图表外框,以及右下角描述内容
  • 去掉X Y轴实线,以及左侧Y轴
  • X轴改为日期显示
  • Y轴网格线改为虚线
  • Y轴值改为百分比,且间隔值为10%
  • 靠近Y轴的柱状图未展示完整
  • 负数值的柱状图未展示完整

去掉图表外框,描述内容以及X Y轴线条

不显示图表边框

barChart.setDrawBorders(false);

不显示右下角内容

Description description = new Description();
description.setEnabled(false);
barChart.setDescription(description);

不显示X轴 Y轴线条

xAxis.setDrawAxisLine(false);
leftAxis.setDrawAxisLine(false);
rightAxis.setDrawAxisLine(false);

不显示左侧Y轴

leftAxis.setEnabled(false);

修改X Y轴网格线

虽然我们设置了不显示与图表网格线

barChart.setDrawGridBackground(false);

但是因为X Y轴还有自己的网格线,所以看起来图表的网格线仍然存在,所以还需对X轴Y轴的网格线进行设置

//不显示X轴网格线
xAxis.setDrawGridLines(false);
//右侧Y轴网格线设置为虚线
rightAxis.enableGridDashedLine(10f, 10f, 0f);

柱状图显示不完整问题解决

在这里柱状图未显示完整,完全是我自己的问题,如果在 initBarChart(BarChart barChart) 方法中不设置X轴Y轴,柱状图默认情况下是能显示完整的。

只需要在前面的基础上 删除 以下代码即可完整展示。

xAxis.setAxisMinimum(0f);
//保证Y轴从0开始,不然会上移一点
leftAxis.setAxisMinimum(0f);
rightAxis.setAxisMinimum(0f);

多条柱状图

多条柱状图展示

多条柱状图,只是多添加一个BarDataSet对象即可。

修改之后代码

   public void showBarChart(final List<String> xValues, LinkedHashMap<String, List<Float>> dataLists,
                              List<Integer> colors) {
        /**
         * @param xValues   X轴的值
         * @param dataLists LinkedHashMap<String, List<Float>>
         *                  key对应柱状图名字  List<Float> 对应每类柱状图的Y值
         * @param colors
         */
            List<IBarDataSet> dataSets = new ArrayList<>();
            int currentPosition = 0;//用于柱状图颜色集合的index

            for (LinkedHashMap.Entry<String, List<Float>> entry : dataLists.entrySet()) {
                String name = entry.getKey();
                List<Float> yValueList = entry.getValue();

                List<BarEntry> entries = new ArrayList<>();

                for (int i = 0; i < yValueList.size(); i++) {
                    entries.add(new BarEntry(i, yValueList.get(i)));
                }
                // 每一个BarDataSet代表一类柱状图
                BarDataSet barDataSet = new BarDataSet(entries, name);
                initBarDataSet(barDataSet, colors.get(currentPosition));
                dataSets.add(barDataSet);

                currentPosition++;
            }

            //X轴自定义值
//            xAxis.setValueFormatter(new IAxisValueFormatter() {
//                @Override
//                public String getFormattedValue(float value, AxisBase axis) {
//                    return xValues.get((int) value % xValues.size());
//                }
//            });
        //将X轴的值显示在中央
        xAxis.setAxisMinimum(0f);
        xAxis.setAxisMaximum(xValues.size());
        xAxis.setCenterAxisLabels(true);


        //X轴自定义值
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xValues.get((int) Math.abs(value) % xValues.size());
            }
        });
            //右侧Y轴自定义值
            rightAxis.setValueFormatter(new IAxisValueFormatter() {
                @Override
                public String getFormattedValue(float value, AxisBase axis) {
                    return (int) (value) + "%";
                }
            });

            BarData data = new BarData(dataSets);

        int barAmount = dataLists.size(); //需要显示柱状图的类别 数量
//设置组间距占比30% 每条柱状图宽度占比 70% /barAmount  柱状图间距占比 0%
        float groupSpace = 0.3f; //柱状图组之间的间距
        float barWidth = (1f - groupSpace) / barAmount;
        float barSpace = 0f;
//设置柱状图宽度
        data.setBarWidth(barWidth);
//(起始点、柱状图组间距、柱状图之间间距)
        data.groupBars(0f, groupSpace, barSpace);

        barChart.setData(data);

    }

调用

   LinkedHashMap<String, List<Float>> chartDataMap = new LinkedHashMap<>();
        List<String> xValues = new ArrayList<>();
        List<Float> yValue1 = new ArrayList<>();
        List<Float> yValue2 = new ArrayList<>();
        List<Integer> colors = Arrays.asList(
                getResources().getColor(R.color.blue), getResources().getColor(R.color.orange)
        );



        for (int i = 0; i < 5; i++) {
            xValues.add("2018/05/"+i);
            yValue1.add((float) 10+i*2);
            yValue2.add((float) 10+i);
        }

        chartDataMap.put("净资产收益率(%)", yValue1);
        chartDataMap.put("行业平均值(%)", yValue2);

        showBarChart(xValues, chartDataMap, colors);

效果图

这是简化之后的  细节的可以到原博客中查看

发布了30 篇原创文章 · 获赞 12 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/smallredzi/article/details/82707352
今日推荐