MPAndroidChart初次使用(3)——柱状图

效果图

在这里插入图片描述

1. 添加依赖

repositories {
    maven { url 'https://jitpack.io' }
}
dependencies {
    implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
}

2. XML界面

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

3. 实现代码

//        条状图
        BarChart barChart = (BarChart)root.findViewById(R.id.bar_chart);
        List<BarEntry> barEntryList = new ArrayList<>();

        barEntryList.add(new BarEntry(1,11));
        barEntryList.add(new BarEntry(2,36));
        barEntryList.add(new BarEntry(3,23));
        barEntryList.add(new BarEntry(4,15));
        barEntryList.add(new BarEntry(5,12));
        barEntryList.add(new BarEntry(6,15));
        barEntryList.add(new BarEntry(7,110));

        BarDataSet barDataSet = new BarDataSet(barEntryList, "");
//        设置颜色(7个柱子,7个颜色)
        List<Integer> colors = new ArrayList<Integer>();
        colors.add(getResources().getColor(R.color.context_title_bg));
        colors.add(getResources().getColor(R.color.context_title_bg));
        colors.add(getResources().getColor(R.color.context_title_bg));
        colors.add(getResources().getColor(R.color.context_title_bg));
        colors.add(getResources().getColor(R.color.context_title_bg));
        colors.add(getResources().getColor(R.color.context_title_bg));
        colors.add(getResources().getColor(R.color.context_title_bg));
        barDataSet.setColors(colors);


        BarData barData = new BarData(barDataSet);
        barChart.setData(barData);

        barData.setValueTextSize(10);

//        去除description
        barChart.getDescription().setEnabled(false);
//        去除 Legend
        barChart.getLegend().setEnabled(false);
//        去除对图标的触摸操作,如果没有去除,可以通过触摸对折线图进行
//        放大,缩小等操作。
        barChart.setTouchEnabled(false);


//        X轴处理
        XAxis barXaxis = barChart.getXAxis();
//        设置X轴的位置为正下方
        barXaxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//        自定义X轴上的刻度显示
        barXaxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return  "12/" + (int) value;
            }
        });

//        Y轴处理
        YAxis barYaxis = barChart.getAxis(YAxis.AxisDependency.LEFT);
        barYaxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return (int) value + "分";
            }
        });
//        隐藏右侧Y轴
        barChart.getAxisRight().setEnabled(false);
注意的问题

几个柱子几个颜色。因为需要柱子都单色,所以七个颜色都设置成一样的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值