效果图:
1、在项目gradle中引入MPAndroidChart
allprojects {
repositories {
maven { url 'https://jitpack.io' }
google()
jcenter()
}
}
dependencies {
//mpandroidchart
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
}
2、柱状图布局xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.github.mikephil.charting.charts.BarChart
android:id="@+id/bar_chart"
android:layout_width="match_parent"
android:layout_height="match_parent"></com.github.mikephil.charting.charts.BarChart>
</LinearLayout>
3、新建BarChartActivity
import androidx.annotation.ColorRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.graphics.Color;
import android.os.Bundle;
import com.github.mikephil.charting.charts.BarChart;
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.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
public class BarChartActivity extends AppCompatActivity {
private BarChart barChart;
private YAxis leftAxis; //左侧Y轴
private YAxis rightAxis; //右侧Y轴
private XAxis xAxis; //X轴
private Legend legend; //图例
private LimitLine limitLine; //限制线
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bar_chart);
barChart = findViewById(R.id.bar_chart);
initBarChart(barChart);
//处理数据是 记得判断每条柱状图对应的数据集合 长度是否一致
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(
ContextCompat.getColor(this,R.color.blue),getResources().getColor(R.color.orange)
);
//换为网络请求数据
xValues.add("蔬菜");
xValues.add("肉类");
xValues.add("牛奶");
xValues.add("蔬菜1");
xValues.add("肉类1");
xValues.add("牛奶1");
xValues.add("蔬菜2");
xValues.add("肉类2");
xValues.add("牛奶2");
yValue1.add((float)4.4);
yValue2.add((float)1.9);
yValue1.add((float)6.4);
yValue2.add((float)0.9);
yValue1.add((float)8.4);
yValue2.add((float)4.9);
yValue1.add((float)4.4);
yValue2.add((float)1.9);
yValue1.add((float)6.4);
yValue2.add((float)0.9);
yValue1.add((float)8.4);
yValue2.add((float)4.9);
yValue1.add((float)4.4);
yValue2.add((float)1.9);
yValue1.add((float)6.4);
yValue2.add((float)0.9);
yValue1.add((float)8.4);
yValue2.add((float)4.9);
chartDataMap.put("标准值", yValue1);
chartDataMap.put("实际值", yValue2);
showBarChart(xValues, chartDataMap, colors);
//请求数据变化时刷新
barChart.invalidate();
}
/**
* 初始化BarChart图表
*/
private void initBarChart(BarChart barChart) {
/***图表设置***/
//背景颜色
barChart.setBackgroundColor(Color.WHITE);
//不显示图表网格
barChart.setDrawGridBackground(false);
//背景阴影
barChart.setDrawBarShadow(false);
barChart.setHighlightFullBarEnabled(false);
barChart.setDoubleTapToZoomEnabled(false);
//支持左右滑动
barChart.setDragEnabled(true);
//X轴或Y轴禁止缩放
barChart.setScaleXEnabled(false);
barChart.setScaleYEnabled(false);
barChart.setScaleEnabled(false);
//不显示边框
barChart.setDrawBorders(false);
//不显示右下角描述内容
Description description = new Description();
description.setEnabled(false);
barChart.setDescription(description);
/***XY轴的设置***/
//X轴设置显示位置在底部
xAxis = barChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setGranularity(1f);
leftAxis = barChart.getAxisLeft();
rightAxis = barChart.getAxisRight();
//不绘制 Y轴线条
rightAxis.setDrawAxisLine(false);
//不显示X轴网格线
xAxis.setDrawGridLines(false);
leftAxis.setDrawGridLines(false);
rightAxis.setDrawGridLines(false);
/***折线图例 标签 设置***/
legend = barChart.getLegend();
legend.setForm(Legend.LegendForm.SQUARE);
legend.setTextSize(11f);
//显示位置
legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
//是否绘制在图表里面
legend.setDrawInside(false);
}
/**
* 柱状图始化设置 一个BarDataSet 代表一列柱状图
*
* @param barDataSet 柱状图
* @param color 柱状图颜色
*/
private void initBarDataSet(BarDataSet barDataSet, int color) {
barDataSet.setColor(color);
barDataSet.setFormLineWidth(1f);
barDataSet.setFormSize(15.f);
}
/**
* @param xValues X轴的值
* @param dataLists LinkedHashMap<String, List<Float>>
* key对应柱状图名字 List<Float> 对应每类柱状图的Y值
* @param colors
*/
public void showBarChart(final List<String> xValues, LinkedHashMap<String, List<Float>> dataLists,
@ColorRes List<Integer> 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++) {
/**
* 如果需要添加TAG标志 可使用以下构造方法
* BarEntry(float x, float y, Object data)
* e.getData()
*/
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) Math.abs(value) % xValues.size());
}
});
xAxis.setLabelRotationAngle(-60);//x轴文字斜体显示
rightAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return "";
}
});
BarData data = new BarData(dataSets);
/**
* float groupSpace = 0.3f; //柱状图组之间的间距
* float barSpace = 0.05f; //每条柱状图之间的间距 一组两个柱状图
* float barWidth = 0.3f; //每条柱状图的宽度 一组两个柱状图
* (barWidth + barSpace) * 2 + groupSpace = (0.3 + 0.05) * 2 + 0.3 = 1.00
* 3个数值 加起来 必须等于 1 即100% 按照百分比来计算 组间距 柱状图间距 柱状图宽度
*/
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);
//设置柱状图一页显示的范围(0-5)
barChart.setVisibleXRange(0,5);
//解决x轴标签斜体显示不全的问题
barChart.notifyDataSetChanged();
xAxis.setAxisMinimum(0f);
xAxis.setAxisMaximum(xValues.size());
//将X轴的值显示在中央
xAxis.setCenterAxisLabels(true);
}
}