Android中MPAndroidChart图表工具的常用方法(汇总)

本篇主要是MPAndroidChart图表工具常用方法的汇总,其他不清楚的可以去GitHub上的文档查询。

强大的图表绘制工具,支持折线图、面积图、散点图、时间图、柱状图、条图、饼图、气泡图、圆环图、范围(高至低)条形图、网状图等;支持图的拖拽缩放;支持 Android 2.2 以上,支持横纵轴缩放,多指缩放,展现动画、高亮、保存到 sdcard、从文件读取图表
项目地址:https://github.com/PhilJay/MPAndroidChart

效果图如下:

alt tag
 

alt tag alt tag

以下为一些常用的方法:

以曲线图为例
依赖:project build.gradle 中
allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}
app build.gradle 中

/*强大的图表绘制工具 */
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'

最简单的代码
<RelativeLayout
    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.LineChart
        android:id="@+id/lineChart"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_centerInParent="true"/>
</RelativeLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    LineChart mLineChart = (LineChart) findViewById(R.id.lineChart);
    //显示边界
    mLineChart.setDrawBorders(true);
    //设置数据
    List<Entry> entries = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        entries.add(new Entry(i, (float) (Math.random()) * 80));
    }
    //一个LineDataSet就是一条线
    LineDataSet lineDataSet = new LineDataSet(entries, "温度");
    LineData data = new LineData(lineDataSet);
    mLineChart.setData(data);
}
效果图:


一.XAxis(X轴)
1.得到X轴:
XAxis xAxis = mLineChart.getXAxis();
2.设置X轴的位置(默认在上方):
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//值:BOTTOM,BOTH_SIDED,BOTTOM_INSIDE,TOP,TOP_INSIDE
3.设置X轴坐标之间的最小间隔(因为此图有缩放功能,X轴,Y轴可设置可缩放)
xAxis.setGranularity(1f);
对比图:左图X轴在图缩放时值的间隔会按比例改变,而右图进行设置后,最小间隔始终为1

4.设置X轴的刻度数量
xAxis.setLabelCount(12, true);
第二个参数表示是否平均分配 如果为true则按比例分为12个点、如果为false则适配X刻度的值来分配点,可能没有12个点。
对比图:左图的参数为true,右图的参数为false

5.设置X轴的值(最小值、最大值、然后会根据设置的刻度数量自动分配刻度显示)
xAxis.setAxisMinimum(0f);
xAxis.setAxisMaximum(20f);
前面是的X轴是根据(X,Y)的值默认显示的X轴,现在才是真正的设置规定的值
效果图:

6.设置X轴值为字符串(如上右图)
xAxis.setValueFormatter(new IAxisValueFormatter() {
    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        return mList.get((int) value); //mList为存有月份的集合
    }
});
想要显示完整的12个月份,要与(x,y)坐标对应数量 10 改成 12
for (int i = 0; i < 12; i++) {
    entries.add(new Entry(i, (float) (Math.random()) * 80));
}
还有设置线条颜色、字体颜色、等等,可查看详细的文档。
7.取消曲线显示的值为整数
与设置自定义X轴类似,设置曲线显示值为整数,可在设置曲线LineDataSet 时,修改值的类型
lineDataSet.setValueFormatter(new IValueFormatter() {
    @Override
    public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
        int IValue = (int) value;
        return String.valueOf(IValue);
    }
});
二.YAxis(Y轴)
如上面的图所示,Y轴总会高出X轴一点,并没有从0点开始,因此需要对Y轴进行设置
Y轴和X轴类似
1.得到Y轴
YAxis leftYAxis = mLineChart.getAxisLeft();
YAxis rightYAxis = mLineChart.getAxisRight();
2.设置从Y轴值
leftYAxis.setAxisMinimum(0f);
leftYAxis.setAxisMaximum(100f);

rightYAxis.setAxisMinimum(0f);
rightYAxis.setAxisMaximum(100f);
以及
leftYAxis.setValueFormatter(new IAxisValueFormatter() {
    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        return (int) value + "%";
    }
});
效果图:

3.设置Y轴是否显示(效果如上右图)
rightYAxis.setEnabled(false); //右侧Y轴不显示
4.X轴和Y轴类似,都具有相同的属性方法
rightYAxis.setGranularity(1f);
rightYAxis.setLabelCount(11,false);
rightYAxis.setTextColor(Color.BLUE); //文字颜色
rightYAxis.setGridColor(Color.RED); //网格线颜色
rightYAxis.setAxisLineColor(Color.GREEN); //Y轴颜色

5.限制线LimitLine(如上右图)
LimitLine limitLine = new LimitLine(95,"高限制性"); //得到限制线
limitLine.setLineWidth(4f); //宽度
limitLine.setTextSize(10f);
limitLine.setTextColor(Color.RED);  //颜色
limitLine.setLineColor(Color.BLUE);
rightYAxis.addLimitLine(limitLine); //Y轴添加限制线
三.Legend(图例:即上图所示的曲线图下面的 温度)
1.得到Lengend
Legend legend = mLineChart.getLegend();
2.设置Lengend位置
legend.setTextColor(Color.CYAN); //设置Legend 文本颜色
legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);

3.设置标签是否换行(当多条标签时 需要换行显示、如上右图)
true:可换行。false:不换行
legend.setWordWrapEnabled(true);
4.隐藏Lengend
legend.setEnabled(false);
如下图所示
四.Description(描述)
1.隐藏描述
Description description = new Description();
description.setEnabled(false);
mLineChart.setDescription(description);
2.设置描述内容
Description description = new Description();
description.setText("X轴描述");
description.setTextColor(Color.RED);
mLineChart.setDescription(description);

五.MarkerView
MarkerView可自定义,用于点击图标值时显示想要的内容 效果如上右图
1.自定义MarkerView
public class MyMarkerView extends MarkerView {

    private TextView tvContent;
    private DecimalFormat format = new DecimalFormat("##0");

    public MyMarkerView(Context context) {
        super(context, R.layout.layout_markerview);
        tvContent = (TextView) findViewById(R.id.tvContent);
    }

    @Override
    public void refreshContent(Entry e, Highlight highlight) {
        tvContent.setText(format.format(e.getY()));
        super.refreshContent(e, highlight);
    }

    @Override
    public MPPointF getOffset() {
        return new MPPointF(-(getWidth() / 2), -getHeight() - 10);
    }
}
2.设置显示MarkerView
MyMarkerView mv = new MyMarkerView(this);
mLineChart.setMarkerView(mv);
折线图的线条设置
//一个LineDataSet就是一条线
LineDataSet lineDataSet = new LineDataSet(entries, "温度");
//设置曲线值的圆点是实心还是空心
lineDataSet.setDrawCircleHole(false);
//设置显示值的字体大小
lineDataSet.setValueTextSize(9f);
//线模式为圆滑曲线(默认折线)
lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);

 

此外,整理一下常用的方法:

整理了一下 图表中常用的一些方法

动画:
所有的图表类型都支持下面三种动画,分别是x方向,y方向,xy方向。
•animateX(int durationMillis): x轴方向
•animateY(int durationMillis): y轴方向

•animateXY(int xDuration, int yDuration): xy轴方向

XY轴的绘制
setEnabled(boolean enabled):设置轴是否被绘制。默认绘制,false不会被绘制。
setDrawLabels(boolean enabled):设置为true打开绘制轴的标签。
setDrawAxisLine(boolean enabled): 设置为true,绘制轴线
setDrawGridLines(boolean enabled): 设置为true绘制网格线。

定义轴线样式
setTextColor(int color): 设置轴标签文本颜色。
setTextSize(float size):设置轴标签的字体大小。
setTypeface(Typeface tf):设置轴标签的自定义Typeface(Typeface.createFromAsset(getAssets(), "字体文件名");)
setGridColor(int color): 设置网格线颜色。
setGridLineWidth(float width):设置网格线宽度。
setAxisLineColor(int color):设置此轴的坐标轴的颜色。
setAxisLineWidth(float width): 设置此轴的坐标轴的宽度。
setVisibleXRangeMaximum(float maxXRange):设置x轴最多显示数据条数,(要在设置数据源后调用,否则是无效的)
enableGridDashedLine(float lineLength, float spaceLength, float phase): 显示网格线虚线模式,"lineLength"控制短线条的长度,"spaceLength"控制两段线之间的间隔长度,"phase"控制开始的点。

图表交互设置
setTouchEnabled(boolean enabled): 允许你打开或者关闭与图表的所有触摸交互的情况。设置是否可以触摸,如为false,则不能拖动,缩放等
setDragEnabled(boolean enabled): 打开或关闭对图表的拖动。
setScaleEnabled(boolean enabled):打开或关闭对图表所有轴的的缩放。
setScaleXEnabled(boolean enabled): 打开或关闭x轴的缩放
setScaleYEnabled(boolean enabled): 打开或关闭y轴的缩放。
setPinchZoom(boolean enabled): 如果设置为true,挤压缩放被打开。如果设置为false,x和y轴可以被单独挤压缩放。
setHighlightEnabled(boolean enabled): 如果设置为true,在图表中选中触屏高亮。
setHighlightPerDragEnabled(boolean enabled): 设置为true时允许高亮显示拖动结束的对象在缩放到最下时。默认:true
setHighlightIndicatorEnabled(boolean enabled): 如果设置为true, 指标线(或杆)将展示被选择的线的绘制的值。
自定义轴线的值
setAdjustXLabels(boolean enabled):如果被设置为true,x轴条目将依赖于它自己在进行缩放的时候。如果设置为false,x轴条目将总是保持相同。
setAvoidFirstLastClipping(boolean enabled):如果设置为true,图表将避免第一个和最后一个标签条目被减掉在图表或屏幕的边缘。
setSpaceBetweenLabels(int characters): 设置x轴标签之间的空间字符数,默认是4个。
setPosition(XAxisPosition pos):设置XAxis应该出现的位置。可以选择TOP,BOTTOM,BOTH_SIDED,TOP_INSIDE或者BOTTOM_INSIDE。

setDescription(String desc): 设置表格的描述

• setDrawYValues(boolean enabled): 设置是否显示y轴的值的数据
•setValuePaintColor(int color):设置表格中y轴的值的颜色,但是必须设置setDrawYValues(true)
• setValueTypeface(Typeface t):设置字体
• setValueFormatter(DecimalFormat format): 设置显示的格式
• setPaint(Paint p, int which): 自定义笔刷
•public ChartData getDataCurrent():返回ChartData对象当前显示的图表。它包含了所有信息的显示值最小和最大值等

setStartAtZero(boolean enabled):如果这个打开,轴线总是有最小值0,无论什么类型的图表被展示。
setAxisMaxValue(float max):设置一个自定义的最大值为这条轴,如果设置了,这个值将不会依赖于提供的数据自动计算。
resetAxisMaxValue(): 调用这个将撤销以前设置的最大值。这意味着,你将再次允许轴自动计算它的最大值。
setAxisMinValue(float min): 设置一个自定义的最小值。如果设置了,这个值将不会依赖于你提供的数据进行自动计算。
resetAxisMinValue():调用这个方法撤销以前设置的最小值。这意味着,你将再次允许轴自动计算他的最小值。
setInverted(boolean enabled): 如果设置为true,这个轴将被反向,那意味着最高出的将到底部,最低部的到顶端。
setSpaceTop(float percent):设置在图表上最高处的值相比轴上最高值的顶端空间(总轴范围的百分比)
setSpaceBottom(float percent): 设置在图表上最低处的值相比轴上最低处值的底部空间(总轴范围的百分比)
setShowOnlyMinMax(boolean enabled): 如果打开了,这个轴将展示出它的最小值和最大值。这将忽略或者覆盖定义过的label-count。
setPosition(YAxisLabelPosition pos):设置轴标签应该被绘制的位置。INSIDE_CHART或者OUTSIDE_CHART中的一个。 自定义影响轴的数值范围应该在图表被设置数据之前应用。
•public float getYChartMin(): 返回当前最小值
•public float getYChartMax(): 返回当前最大值
•public float getAverage(): 返回所有值的平均值。
•public float getAverage(int type): 返回平均值
•public PointF getCenter(): 返回中间点
•public Paint getPaint(int which): 得到笔刷
•setDragScaleEnabled(boolean enabled): 设置是否可以拖拽,缩放
•setOnChartValueSelectedListener(OnChartValueSelectedListener l): 设置表格上的点,被点击的时候,的回调函数
•public void highlightValues(Highlight[] highs): 设置高亮显示
•saveToGallery(String title): 保存图表到图库中
•saveToPath(String title, String pathOnSD): 保存.
•setScaleMinima(float x, float y): 设置最小的缩放
•centerViewPort(int xIndex, float val): 设置视口

•fitScreen(): 适应屏幕

 

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值