先來看效果
MPAndroidChart在github上地址:https://github.com/PhilJay/MPAndroidChart
1. 依賴:
Project 的build.gradle文件中添加
Project 的build.gradle文件中添加
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
然後在 module中的build,gradle 中添加
dependencies {
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
}
2. 數據準備
{
"vtDateValue": [
{
"fValue": 19,
"sYearMonth": "豆腐"
},
{
"fValue": 14.4348,
"sYearMonth": "魚蝦"
},
{
"fValue": 12.6504,
"sYearMonth": "蔬菜"
},
{
"fValue": 7.9092,
"sYearMonth": "肉類"
},
{
"fValue": 4.3995,
"sYearMonth": "糧食"
}
],
"vtDateValueAvg": [
{
"fValue": 0.95137,
"sYearMonth": "糧食"
},
{
"fValue": 3.50875,
"sYearMonth": "肉類"
},
{
"fValue": 4.62725,
"sYearMonth": "蔬菜"
},
{
"fValue": 1.38761,
"sYearMonth": "魚蝦"
},
{
"fValue": 0.61198,
"sYearMonth": "豆腐"
}
]
}
3 數據展示
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);
BarChartBean barChartBean = LocalJsonAnalyzeUtil.JsonToObject(this,
"bar_chart.json", BarChartBean.class);
//處理數據是 記得判斷每條柱狀圖對應的數據集合 長度是否一致
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)
);
List<BarChartBean.VtDateValueBean> valueList = barChartBean.getVtDateValue();
List<BarChartBean.VtDateValueAvgBean> avgValueList = barChartBean.getVtDateValueAvg();
Collections.reverse(valueList);
for (BarChartBean.VtDateValueBean valueBean : valueList) {
xValues.add(valueBean.getSYearMonth());
yValue1.add((float) valueBean.getFValue());
}
for (BarChartBean.VtDateValueAvgBean valueAvgBean : avgValueList) {
yValue2.add((float) valueAvgBean.getFValue());
}
chartDataMap.put("標準值", yValue1);
chartDataMap.put("實際值", yValue2);
showBarChart(xValues, chartDataMap, colors);
}
/**
* 初始化BarChart圖表
*/
private void initBarChart(BarChart barChart) {
/***圖表設置***/
//背景顏色
barChart.setBackgroundColor(Color.WHITE);
//不顯示圖表網格
barChart.setDrawGridBackground(false);
//背景陰影
barChart.setDrawBarShadow(false);
barChart.setHighlightFullBarEnabled(false);
barChart.setDoubleTapToZoomEnabled(false);
//禁止拖拽
barChart.setDragEnabled(false);
//X軸或Y軸禁止縮放
barChart.setScaleXEnabled(false);
barChart.setScaleYEnabled(false);
barChart.setScaleEnabled(false);
//禁止所有事件
// barChart.setTouchEnabled(false);
//不顯示邊框
barChart.setDrawBorders(false);
//不顯示右下角描述內容
Description description = new Description();
description.setEnabled(false);
barChart.setDescription(description);
//設置動畫效果
barChart.animateY(1000, Easing.Linear);
barChart.animateX(1000, Easing.Linear);
/***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());
}
});
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);
xAxis.setAxisMinimum(0f);
xAxis.setAxisMaximum(xValues.size());
//將X軸的值顯示在中央
xAxis.setCenterAxisLabels(true);
}