[Android Studio] Use of third-party library chart (MPAndroidChart)

1. Add dependencies

Project Directory->app->build.gradle

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

insert image description here

Project Directory->app->setting.gradle

dependencyResolutionManagement {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

insert image description here

2. Chart class

​ This class is the control of the chart, similar to buttons and pictures, and is obtained from the xml file through the id.

get/create

xxxChart chart = (xxxChart) findViewById(R.id.chart);

common method

method name describe
chart.setDrawBorders(boolean) Whether to display the chart border, true: display, default false
chart.setScaleEnabled(boolean) Whether to enable scaling, true: enable, default false
chart.setScaleXEnabled(boolean) Whether to enable zooming in the X-axis direction, true: enable, default false
chart.setScaleYEnabled(boolean) Whether to enable scaling in the Y-axis direction, true: enable, default false
chart.setExtraRightOffset(float) Set the offset of the right border of the chart (to solve the problem of incomplete display of the X-axis)
chart.setExtraLeftOffset(float) Set the offset of the left border of the chart (to solve the problem of incomplete display of the X-axis)
chart.setExtraBottomOffset(float) Sets the offset of the bottom border of the chart
chart.setExtraTopOffset(float) Sets the offset of the chart's top border
chart.setOnChartValueSelectedListener
(OnChartValueSelectedListener)
Listen to click data events in the chart (see 10, OnChartValueSelectedListener interface for details))
chart.setData(-Data) Insert a set of data into the chart (see 3, DataSet class for details))
chart.getXAxis() Get the x-axis of the chart
chart.setVisibleXRangeMaximum(float) Set the maximum amount of tick marks displayed on the X-axis coordinate line in the current chart
chart.getAxisLeft() Get the Y-axis on the left side of the chart
chart.getAxisRight() Get the Y-axis on the right side of the chart
chart.getLegend() Get the legend for the chart
chart.setDescription() Set the chart title
chart.animateY(int) Set the animation time (milliseconds) to play in the Y-axis direction
chart.animateX(int) Set the animation time (milliseconds) to play in the direction of the X axis
chart.animateXY(int) Set the animation time (milliseconds) to play in the XY axis direction
chart.notifyDataSetChanged() Let the chart know that it is called when the dependent data changes, and the chart will be recalculated after the call, which is useful when using dynamic data
chart.invalidate() This method refreshes the chart and will redraw it. It must be called after changing the chart to take effect

3. DataSet class

effect

​Set some representations of a set of data displayed on the chart . For example, set the color, thickness, etc. of the polyline.

Constructor

xxxDataSet dataSet = new xxxDataSet(List<Entry> yVals, String label);
  • yVals : A set of data that needs to be displayed

  • label : the name of the set of data

The origin of the yVals list array:

float[] data;

// 填充数据
for(int i = 0; i < data.length; i++) {
    
    
    // 两个数字对应的分别是 X轴 Y轴
    barList.add(new BarEntry(i, data[i]));
}

shared method

method name describe
dataSet.setColor(int) Set the color of the polyline/column, the color can be obtained by Color.parseColor("#xxxxxx")
dataSet.setValueTextSize(float) Set font size on polyline points/columns
dataSet.setValueFormatter( IValueFormatter ) Re-display the data on the polyline point/column, and add units (see 8, IValueFormatter interface for details))
dataSet.setHighlightEnabled(boolean) Whether the selected data is highlighted, true: highlighted, default true
dataSet.setHighLightColor(int) Set the highlight color (this setting has no effect if it is not highlighted)
dataSet.addEntry(Entry) Add an Entry object (data) to the DataSet
dataSet.removeFirst() Delete the first Entry object (data) of the DataSet
dataSet.removeLast() 删除 DataSet 的最后一个 Entry 对象(数据)
dataSet.removeEntry(Entry)
dataSet.removeEntry(int xIndex)
删除指定的一个 Entry 对象(数据)

3.1 LineDataSet

方法名 描述
lineDataSet.setLineWidth(float) 设置折线的宽度
lineDataSet.setCircleColor(int) 设置折线点的颜色,颜色可以通过Color.parseColor(“#xxxxxx”) 得到
lineDataSet.setCircleRadius(float) 设置折线点的半径
lineDataSet.setDrawCircleHole(boolean) 是否将折线点画成空心圆,true:画成空心圆,默认 false
lineDataSet.setCircleHoleRadius(float) 设置折线点空心圆的圆心半径(如果没有设置成空心圆,该设置无效)
lineDataSet.setCircleColorHole(int) 设置折线点空心圆内部的颜色(如果没有设置成空心圆,该设置无效)
lineDataSet.setHighlightLineWidth(float) 设置高亮指示线宽度(如果不高亮显示,该设置无效)

3.2 BarDataSet

方法名 描述
barDataSet.setBarBorderColor(int) 设置柱子边框颜色,颜色可以通过
Color.parseColor(“#xxxxxx”) 得到
barDataSet.setBarBorderWidth(float) 设置柱子边框厚度
barDataSet.setHighLightAlpha(int) 设置柱子高亮显示时的颜色透明度,0:完全透明,
255:完全不透明(如果不高亮显示,该设置无效)

4、Data 类

​ ChartData 类是所有图表数据类的基类

public class LineData extends ChartData {
    
     ...

作用

​ **将一个或若干个 -DataSet 数据类做进一步的包装,由 -Data 类进行管理。**并通过它传递给 -Chart 类进行显示。

构造方法

xxxData data = new xxxData(IBarDataSet DataSet);
  • DataSet:前面提到的 xxxDataSet 数据类。

共用方法

方法名 描述
data.addDataSet(DataSet) 添加一组新的数据(动态添加数据的时候使用)(详见 3、DataSet 类))
data.addEntry(Entry e, int dataSetIndex) 将 Entry 对象添加到内部的某一个 DataSet(由 dataSetIndex 决定)中去
data.removeDataSet(DataSet)
data.removeDataSet(**int **index)
删除指定的一个 DataSet
data.setValueFormatter(IValueFormatter) 对折线点/柱子上的数据重新进行显示,可以实现加单位(详见 8、IValueFormatter 接口))
data.setDrawValues(boolean) 是否显示各个数据的值,false:不显示,默认 true

4.1 BarChart

方法名 描述
barChart.setBarWidth(float) 设置柱子宽度,一般不超过 1 就可以了

5、AxisBase 类

作用

​ 该类是 Chart 图表的 X/Y 轴的基类。

共用方法

方法名 描述
Axis.setTextSize(float) 设置坐标轴的字体大小
Axis.setAxisLineColor(int) 设置坐标轴的字体颜色,颜色可以通过
Color.parseColor(“#xxxxxx”) 得到
Axis.setAxisLineWidth(float) 设置坐标轴的粗细
Axis.setValueFormatter(IAxisValueFormatter) 重新格式化坐标轴标签(值)(详见 9、IAxisValueFormatter 接口))
Axis.setAxisMinimum(float) Axis.setAxisMaximum(float) 设置坐标轴显示的区间
Axis.setGranularity(float) 设置坐标轴坐标之间的最小间隔
Axis.setLabelCount(int) 设置坐标轴总共有多少个值
Axis.addLimitLine(LimitLine) 向坐标轴上添加一条新的限制线(详见 6、LimitLine 类))
Axis.removeLimitLine(LimitLine) 从坐标轴上移除一条限制线(详见 6、LimitLine 类))
Axis.setDrawLimitLinesBehindData(boolean) 设置限制线和数据标签的图层顺序,true:限制线将绘制在数据的后面,否则绘制在前面,默认为 false
Axis.setDrawGridLines(boolean) 是否绘制坐标轴的网格线,false:不绘制,默认 true
Axis.setGridColor(int) 设置坐标轴的网格线的颜色,颜色可以通过
Color.parseColor(“#xxxxxx”) 得到

5.1 XAxis

作用

​ 该类是 Chart 图表的 X 轴,由 chart.getXAxis() 获取。

常用方法

方法名 描述
xAxis.setPosition(XAxis.XAxisPosition.xxx) 设置 X 轴的位置。可取:BOTTOM、BOTH_SIDED BOTTOM_INSIDE、TOP、TOP_INSIDE
xAxis.setLabelCount(int) 设置 X 轴总共有多少个值,一般该方法后面跟着
chart.setVisibleXRangeMaximum(float)
xAxis.setLabelRotationAngle(float) 设置 X 轴标签数据旋转的角度

5.2 YAxis

作用

​ 该类是 Chart 图表的 Y 轴,但 Chart 中有左右两个 Y 轴,分别由 chart.getAxisLeft()、chart.getAxisRight() 获取。

常用方法

方法名 描述
yAxis.setEnabled(boolean) 设置该 Y 轴是否显示,false:不显示,默认显示
yAxis.setInverted(boolean) 设置是否倒置高低值,true:大值将会在底部出现,小值将会在顶部出现,默认 false

6、LimitLine 类

作用

​ 该类是 Chart 的限制线,作用是呈现一些特殊的信息,像边界、约束等。

构造函数

LimitLine limitLine = new LimitLine(float limit, String label);
  • limit:这条线应该出现在坐标轴上的位置(值)

  • label:该限制线的名字

常用方法

方法名 描述
limitLine.setLabelPosition(LimitLine.LimitLabelPosition.xxx) 设置限制线描述字符串的位置,可以取值:LEFT_TOP, LEFT_BOTTOM, RIGHT_TOP, RIGHT_BOTTOM
limitLine.setLineWidth(float) 设置限制线的宽度
limitLine.setTextSize(float) 设置限制线描述字符串的大小
limitLine.setTextColor(int) 设置限制线描述字符串的颜色,颜色可以通过Color.parseColor(“#xxxxxx”) 得到
limitLine.setLineColor(int) 设置限制线的颜色,颜色可以通过
Color.parseColor(“#xxxxxx”) 得到

7、Description 类

作用

​ 该类是一个 Chart 类的标题。

构造函数

Description description = new Description();

常用方法

方法名 描述
description.setText(String) 设置图表标题名
description.setTextSize(float) 设置图表标题大小
description.setPosition(float x, float y) 设置图表标题位置

8、IValueFormatter 接口

作用

​ 对数据组 DataSet 中的数据标签进行重新格式化。

例子

DataSet.setValueFormatter(new IValueFormatter() {
    
    
    @Override
    public String getFormattedValue(float v, Entry entry, int i, ViewPortHandler viewPortHandler) {
    
    
        if(entry.getY() == v){
    
    
            return v + "h";
        }
        return "";
    }
});
  • v:要格式化的值
  • enry:值所属的条目

9. IAxisValueFormatter interface

effect

​ Reformat the labels of the axes.

example

String[] data;
    
Axis.setValueFormatter(new IAxisValueFormatter() {
    
    
    @Override
    public String getFormattedValue(float value, AxisBase axis) {
    
    
        if((int)value >= 0 && (int)value < data.length) {
    
    
            return data[(int) value];
        }
        return "";
    }
});
  • value : the value to format

10. OnChartValueSelectedListener interface

effect

​ Monitor whether the data in the data group is clicked. You can click on different data in this listening function to display the corresponding different data in another Chart.

example

chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
    
    
    // 点击数据后的回调函数
    @Override
    public void onValueSelected(Entry entry, Highlight highlight) {
    
    
        int iEntry = (int) entry.getX();
    }
	
    // 取消点击数据后的回调函数
    @Override
    public void onNothingSelected() {
    
    

    }
});

11. Examples

insert image description here

    <com.github.mikephil.charting.charts.BarChart
        android:id="@+id/bar"
        android:layout_marginTop="50dp"
        android:layout_width="380dp"
        android:layout_height="258dp"
        android:layout_gravity="center" >
    </com.github.mikephil.charting.charts.BarChart>
// x轴
String[] day = {
    
    "1-1", "1-2", "1-3", "1-4", "1-5", "1-6", "1-7"};
// x轴对应的数据
float[] time = {
    
    (float)6.8, (float)5.4, (float)2.9, (float)8.2, (float)4.7, (float)6.1, (float)9.2};
// 实例化一个List用来存储数据
List<BarEntry> barList = new ArrayList<>();


/*柱状图*/
mBarChart = (BarChart) findViewById(R.id.bar);
// 是否使能缩放
mBarChart.setScaleEnabled(false);
mBarChart.setExtraLeftOffset(10);
mBarChart.setExtraTopOffset(50);
// 动画
mBarChart.animateY(1000);

/** 柱子 **/
// 填充数据
for(int i = 0; i < time.length; i++) {
    
    
    // 两个数字对应的分别是 X轴 Y轴
    barList.add(new BarEntry(i, time[i]));
}
// 设置该组数据名称
BarDataSet barDataSet = new BarDataSet(barList,"时长");
// 设置柱子颜色
barDataSet.setColors(Color.parseColor("#D2B48C"));
// 柱子边框颜色
barDataSet.setBarBorderColor(Color.parseColor("#CD853F"));
// 柱子边框厚度
barDataSet.setBarBorderWidth(2);
// 设置柱子高亮显示时的颜色透明度,当不高亮显示时,该设置无效
barDataSet.setHighLightAlpha(100);
// 设置柱子上字体大小
barDataSet.setValueTextSize(11);
// 定义柱子上的数据显示,可以实现加单位
barDataSet.setValueFormatter(new IValueFormatter() {
    
    
    @Override
    public String getFormattedValue(float v, Entry entry, int i, ViewPortHandler viewPortHandler) {
    
    
        if(entry.getY() == v){
    
    
            return v + "h";
        }
        return "";
    }
});
BarData barData = new BarData(barDataSet);
// 设置柱子宽度
barData.setBarWidth(0.7f);
mBarChart.setData(barData);

/** X轴 **/
XAxis xAxis = mBarChart.getXAxis();
// 设置X轴的位置  BOTTOM  BOTH_SIDED  BOTTOM_INSIDE  TOP  TOP_INSIDE
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
// 设置X轴坐标之间的最小间隔
xAxis.setGranularity(1);
// 设置X轴的刻度数量
xAxis.setLabelCount(day.length);
// 设置当前图表中最多在x轴坐标线上显示刻度线的总量
mBarChart.setVisibleXRangeMaximum(8);
// 设置X轴的字体大小
xAxis.setTextSize(11);
// 设置X轴的字体颜色
xAxis.setAxisLineColor(Color.BLACK);
// 设置X轴的粗细
xAxis.setAxisLineWidth(1);
// 是否绘制X轴的网格线
xAxis.setDrawGridLines(false);
// 给X轴设置新的标签(值)
xAxis.setValueFormatter(new IAxisValueFormatter() {
    
    
    @Override
    public String getFormattedValue(float value, AxisBase axis) {
    
    
        if((int)value >= 0 && (int)value < day.length) {
    
    
            return day[(int)value];
        }
        return "";
    }
});

/** Y轴 **/
YAxis leftYAxis = mBarChart.getAxisLeft();
YAxis rightYAxis = mBarChart.getAxisRight();
// 设置某一个Y轴是否显示
rightYAxis.setEnabled(false);
// 设置Y轴显示的区间
leftYAxis.setAxisMinimum(0);
leftYAxis.setAxisMaximum(10);
// 设置Y轴值之间的间隔
leftYAxis.setGranularity(2);
// 设置Y轴总共有多少个值
leftYAxis.setLabelCount(6);
// 设置Y轴字体大小
leftYAxis.setTextSize(11);
// 设置Y轴字体颜色
leftYAxis.setAxisLineColor(Color.BLACK);
// 设置Y轴的粗细
leftYAxis.setAxisLineWidth(1f);
// 给Y轴设置新的标签(值)
leftYAxis.setValueFormatter(new IAxisValueFormatter() {
    
    
    @Override
    public String getFormattedValue(float v, AxisBase axisBase) {
    
    
        return (int)v + "h";
    }
});

/** 限制线 **/
// 创建一个新的限制线
LimitLine limitLine = new LimitLine(8,"限制线");
// 设置限制线的宽度
limitLine.setLineWidth(2);
limitLine.setTextSize(11);
limitLine.setTextColor(Color.parseColor("#B22222"));
limitLine.setLineColor(Color.RED);
leftYAxis.addLimitLine(limitLine);

/** 图例 **/
Legend legend = mBarChart.getLegend();
// 设置图例的文本颜色
legend.setTextColor(Color.BLACK);
legend.setTextSize(12);

/** 图表标题 **/
Description description = new Description();
description.setText("图表标题");
description.setTextSize(17);
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
int w = windowManager.getDefaultDisplay().getWidth();
description.setPosition(w / 2 + 100, 90);
mBarChart.setDescription(description);

Guess you like

Origin blog.csdn.net/weixin_48896613/article/details/129877286