MPAndroidChart文檔

開(kāi)始

添加依賴

在第一步,需要將依賴的庫(kù)添加到你的項(xiàng)目中

創(chuàng)建View

想要使用 LineChart,BarChart,ScatterChart,CandleStickChart,PieChart,BubbleChart或者RadarChart,需要先在xml中定義

<com.github.mikephil.charting.charts.LineChart
     android:id="@+id/chart"
     android:layout_width="match_parent"
     android:layout_height="match_parent" />

然后在你的Activity或者Fragment中獲取控件

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

或者使用代碼創(chuàng)建,在布局中添加

LineChart chart = new LineChart(Context);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
rl.add(chart);

添加數(shù)據(jù)

在你擁有了圖表的實(shí)例之后,你可以創(chuàng)建數(shù)據(jù)并添加到圖表中.下面是一個(gè)使用折線圖的例子,每一條數(shù)據(jù)都可以使用Entry這個(gè)類來(lái)標(biāo)識(shí)x,y坐標(biāo).
在其他圖表類型中,比如BarChart使用其他的類(比如BarEntry)來(lái)達(dá)到相同的目的.

添加數(shù)據(jù)到圖表中,需要將所有的數(shù)據(jù)都包裹在Entry對(duì)象中

YourData[] dataObjects = ...;

List<Entry> entries = new ArrayList<Entry>();

for (YourData data : dataObjects) {
    entries.add(new Entry(data.getValueX(), data.getValueY())); 
}

然后,你需要給你創(chuàng)建的LineDataSet對(duì)象添加List<Entry>數(shù)據(jù)集合,DataSet對(duì)象持有數(shù)據(jù),這些數(shù)據(jù)用戶可以自定義樣式.
下面的"Label"用于描述數(shù)據(jù)的作用,如果圖例開(kāi)啟的話,還會(huì)作為圖例顯示在圖表上

LineDataSet dataSet = new LineDataSet(entries, "Label"); // 添加數(shù)據(jù)
dataSet.setColor(...);
dataSet.setValueTextColor(...); // 自定義數(shù)據(jù)樣式

最后一步,你需要把創(chuàng)建好的LineDataSet添加到LineData中,添加完數(shù)據(jù),利用Chart的實(shí)例去設(shè)置數(shù)據(jù),并且刷新一下

LineData lineData = new LineData(dataSet);
chart.setData(lineData);
chart.invalidate(); // 刷新




圖表的交互

這個(gè)庫(kù)可以讓你最大限度的通過(guò)手勢(shì)觸摸與圖表交互,并且通過(guò)回調(diào)函數(shù)獲取反饋

開(kāi)啟/關(guān)閉交互

  • setTouchEnabled(boolean enabled): 允許觸摸圖表
  • setDragEnabled(boolean enabled): 允許拖拽圖表
  • setScaleEnabled(boolean enabled): 允許縮放圖表
  • setScaleXEnabled(boolean enabled): 允許以X軸縮放
  • setScaleYEnabled(boolean enabled): 允許以Y軸縮放
  • setPinchZoom(boolean enabled): 如果為true則x和y軸將會(huì)聯(lián)動(dòng)縮放,否則就分開(kāi)縮放
  • setDoubleTapToZoomEnabled(boolean enabled): 若允許則可以雙擊進(jìn)行縮放

圖表滑動(dòng)

  • setDragDecelerationEnabled(boolean enabled): 設(shè)置為true,圖表在手指觸碰滑動(dòng)后,會(huì)有慣性繼續(xù)運(yùn)動(dòng)
  • setDragDecelerationFrictionCoef(float coef): 設(shè)置一個(gè)在[0,1]區(qū)間內(nèi)的滑動(dòng)系數(shù),越高的值代表減速會(huì)越慢,比如設(shè)置為0,在手指滑動(dòng)圖表離開(kāi)后將會(huì)立即停止滑動(dòng),1是一個(gè)不規(guī)范的值,它將會(huì)被自動(dòng)設(shè)置為0.9999

手勢(shì)操作回調(diào)

如果使用手勢(shì)操作圖表,可以使用OnChartGestureListener來(lái)監(jiān)聽(tīng)回調(diào)

public interface OnChartGestureListener {

    //當(dāng)手指剛觸摸到圖表時(shí)觸發(fā),action_down
    void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture);

    //當(dāng)手指在圖表上操作結(jié)束時(shí)調(diào)用,action_up、action_cancel
    void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture);

    //長(zhǎng)按圖表回調(diào)
    public void onChartLongPressed(MotionEvent me);

    //雙擊圖表回調(diào)
    public void onChartDoubleTapped(MotionEvent me);

    //單擊圖表回調(diào)
    public void onChartSingleTapped(MotionEvent me);

    //滑動(dòng)圖表回調(diào)
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY);

    //縮放圖表回調(diào)
    public void onChartScale(MotionEvent me, float scaleX, float scaleY);

    //拖拽圖表回調(diào)
    public void onChartTranslate(MotionEvent me, float dX, float dY);
}

將你的Chart去設(shè)置手勢(shì)監(jiān)聽(tīng)器就可以實(shí)現(xiàn)這些回調(diào)

chart.setOnChartGestureListener(this);




高亮顯示

開(kāi)啟/關(guān)閉高亮

  • setHighlightPerDragEnabled(boolean enabled): 設(shè)置為true時(shí),在圖表完全縮小的情況下,拖拽圖表可以高亮,默認(rèn)為true
  • setHighlightPerTapEnabled(boolean enabled): 設(shè)置為false時(shí),圖表將不會(huì)因?yàn)槭謩?shì)而高亮,拖拽和代碼操作依舊可以觸發(fā)高亮,默認(rèn)為true
  • setMaxHighlightDistance(float distanceDp): 設(shè)置觸發(fā)可以高亮的最遠(yuǎn)距離,觸摸點(diǎn)離圖表過(guò)遠(yuǎn)時(shí),將不會(huì)觸發(fā)高亮

高亮樣式可以由個(gè)人自定義

dataSet.setHighlightEnabled(true); // 是否允許高亮
dataSet.setDrawHighlightIndicators(true); // 設(shè)置是否有拖拽高亮指示器
dataSet.setHighlightColor(Color.BLACK); // 設(shè)置高亮顏色

代碼高亮數(shù)據(jù)

  • highlightValue(float x, int dataSetIndex, boolean callListener): 通過(guò)給的在dataset中的x位置,去高亮數(shù)據(jù).dataSetIndex給-1時(shí),將會(huì)禁止一切高亮,布爾值的callListener標(biāo)識(shí)是否允許監(jiān)聽(tīng)回調(diào)
  • highlightValue(Highlight high, boolean callListener): 通過(guò)傳遞來(lái)的Highlight對(duì)象去高亮數(shù)據(jù),hightlight對(duì)象傳null時(shí)表示不高亮,布爾值的callListener標(biāo)識(shí)是否允許監(jiān)聽(tīng)回調(diào)
  • highlightValues(Highlight[] highs): 傳入一個(gè)Highlight[]數(shù)組以同時(shí)高亮多個(gè)條目,數(shù)組為空或者null時(shí)表示不進(jìn)行高亮
  • getHighlighted(): 返回一個(gè)Highlight[]數(shù)組,里面包含高亮的條目,x軸位置以及在dataset中的位置

選擇回調(diào)

OnChartValueSelectedListener,通過(guò)觸摸高亮數(shù)據(jù)時(shí)的回調(diào)

public interface OnChartValueSelectedListener {
    
    //當(dāng)圖表內(nèi)的一項(xiàng)被選中時(shí)的回調(diào)
    public void onValueSelected(Entry e, Highlight h);
    
    //當(dāng)沒(méi)有選擇項(xiàng)時(shí)的回調(diào)
    public void onNothingSelected();
}

Highlight類

Highlight類,通常被用于獲取高亮條目的信息,或者用來(lái)給圖表或者Entry對(duì)提供數(shù)據(jù)用于高亮,Highlight類提供兩個(gè)構(gòu)造函數(shù)

 //標(biāo)準(zhǔn)的Highlight構(gòu)造函數(shù)
 public Highlight(float x, int dataSetIndex) { ... }

 //給BarEntry使用的Highlight構(gòu)造函數(shù)
 public Highlight(float x, int dataSetIndex, int stackIndex) { ... }

一個(gè)通過(guò)代碼方式利用Highlight進(jìn)行高亮的例子

// highlight the entry and x-position 50 in the first (0) DataSet
Highlight highlight = new Highlight(50f, 0); 

chart.highlightValue(highlight, false); // highlight this value, don't call listener

自定義高亮

所有用戶輸入的手勢(shì)高亮形式都是由默認(rèn)的ChartHighlighter類完成的,通過(guò)自定義ChartHighlighter類的實(shí)現(xiàn)來(lái)替換默認(rèn)的,完成更多的不同的高亮形式
setHighlighter(ChartHighlighter highlighter): 傳入自定義的ChartHighlighter實(shí)現(xiàn)類對(duì)象來(lái)完成高亮樣式的設(shè)置




坐標(biāo)軸

坐標(biāo)軸類通過(guò)以下部分實(shí)現(xiàn)具體的樣式

  • Label 繪制在坐標(biāo)軸旁,包含坐標(biāo)軸的詳細(xì)數(shù)據(jù)
  • axis-line 坐標(biāo)軸線
  • grid-lines 橫向的表格線
  • LimitLines 限制線用于呈現(xiàn)一些特殊的信息,像邊界、約束等

控制坐標(biāo)軸的哪些部分可以被繪制

  • setEnabled(boolean enabled): 坐標(biāo)軸開(kāi)關(guān),設(shè)置為false時(shí),不論其他設(shè)置怎樣都不會(huì)再繪制坐標(biāo)軸
  • setDrawLabels(boolean enabled): 坐標(biāo)值開(kāi)關(guān),設(shè)置為false時(shí)將不會(huì)繪制坐標(biāo)值
  • setDrawAxisLine(boolean enabled): 坐標(biāo)線開(kāi)關(guān),設(shè)置為false時(shí)將不會(huì)繪制坐標(biāo)線
  • setDrawGridLines(boolean enabled): 表格背景線開(kāi)關(guān),設(shè)置為false時(shí)將不會(huì)繪制圖表背景上的表格線

定制坐標(biāo)軸的范圍(最小/最大)

  • setAxisMaximum(float max): 設(shè)置坐標(biāo)軸的最大值,一旦設(shè)置將不會(huì)再自動(dòng)按照提供的值進(jìn)行計(jì)算
  • resetAxisMaximum(): 恢復(fù)默認(rèn)設(shè)置,自己設(shè)置的最大值將不再生效,仍有提供的數(shù)據(jù)進(jìn)行自動(dòng)計(jì)算得到
  • setAxisMinimum(float min): 設(shè)置坐標(biāo)軸的最小值,一旦設(shè)置將不會(huì)再自動(dòng)按照提供的值進(jìn)行計(jì)算
  • resetAxisMinimum(): 恢復(fù)默認(rèn)設(shè)置,自己設(shè)置的最小值將不再生效,仍有提供的數(shù)據(jù)進(jìn)行自動(dòng)計(jì)算得到
  • setInverted(boolean enabled): 倒置高低值,大值將會(huì)在底部出現(xiàn),小值將會(huì)在頂部出現(xiàn)
  • setSpaceTop(float percent): 設(shè)置距頂部的間距(占總軸的范圍的百分比)
  • setSpaceBottom(float percent): 設(shè)置距底部的間距(占總軸的范圍的百分比)
  • setShowOnlyMinMax(boolean enabled): 如果設(shè)置為true,將會(huì)只顯示最小值和最大值,中間的數(shù)據(jù)將會(huì)忽略掉不顯示(如果不是強(qiáng)制顯示的話)
  • setLabelCount(int count, boolean force): 設(shè)置y軸標(biāo)簽數(shù),這個(gè)數(shù)字不是固定的除非force設(shè)置為true,如果force設(shè)置為true會(huì)精確繪制坐標(biāo)值標(biāo)簽數(shù),導(dǎo)致軸上數(shù)字不均勻
  • setPosition(YAxisLabelPosition pos): 設(shè)置縱軸坐標(biāo)值的繪制位置(圖表內(nèi)側(cè)或者圖表外側(cè) --- INSIDE_CHART or OUTSIDE_CHART)
  • setGranularity(float gran): 設(shè)置y軸的最小間距,用于避免縮放到最小時(shí),坐標(biāo)軸上數(shù)據(jù)相互重疊
  • setGranularityEnabled(boolean enabled): 可以在縮放時(shí)限制y軸間距,默認(rèn)false

定制坐標(biāo)軸樣式

  • setTextColor(int color): 設(shè)置坐標(biāo)軸值標(biāo)簽的顏色
  • setTextSize(float size): 設(shè)置坐標(biāo)軸值標(biāo)簽的字體的大小
  • setTypeface(Typeface tf): 給坐標(biāo)軸值標(biāo)簽設(shè)置一個(gè)字體
  • setGridColor(int color): 設(shè)置背景表格線的顏色
  • setGridLineWidth(float width): 設(shè)置背景表格線的寬度
  • setAxisLineColor(int color): 設(shè)置坐標(biāo)軸線的顏色
  • setAxisLineWidth(float width): 設(shè)置坐標(biāo)軸線的寬度
  • enableGridDashedLine(float lineLength, float spaceLength, float phase): 讓背景表格線變成虛線模式就像 - - - - - 的樣子,lineLength控制實(shí)線長(zhǎng)度,spaceLength控制虛線長(zhǎng)度,phase控制起始點(diǎn)

對(duì)坐標(biāo)軸值進(jìn)行格式化

可以使用IAxisValueFormatter接口來(lái)格式化坐標(biāo)軸數(shù)據(jù),使用axis.setValueFormatter(IAxisValueFormatter formatter)設(shè)置自己的定制數(shù)據(jù)格式

限制線

像邊界線和約束線這種用于表示特殊信息的線我們稱之為限制線,限制線在Y軸上橫向呈現(xiàn),在X軸上縱向呈現(xiàn)

  • addLimitLine(LimitLine l): 向坐標(biāo)軸上添加一條新的限制線
  • removeLimitLine(LimitLine l): 從坐標(biāo)軸上移除一條限制線
  • setDrawLimitLinesBehindData(boolean enabled): 允許設(shè)置限制線和數(shù)據(jù)標(biāo)簽的圖層順序,為true的話限制線將繪制在數(shù)據(jù)的后面,否則繪制在前面,默認(rèn)為false

限制線顧名思義是給用戶提供格外信息的一種簡(jiǎn)潔、簡(jiǎn)單的線

例如,您的圖表可能會(huì)顯示用戶的各種血壓測(cè)量結(jié)果.為了通知用戶,收縮壓超過(guò)140毫米汞柱被認(rèn)為是健康風(fēng)險(xiǎn),你可以在140添加一個(gè)限制線來(lái)提供這些信息

YAxis leftAxis = chart.getAxisLeft();

LimitLine ll = new LimitLine(140f, "健康的血壓線");
ll.setLineColor(Color.RED);
ll.setLineWidth(4f);
ll.setTextColor(Color.BLACK);
ll.setTextSize(12f);
// .. 更多的樣式設(shè)置

leftAxis.addLimitLine(ll);




X軸

任何與橫軸有關(guān)的數(shù)據(jù)信息都存放在X軸中,像折線圖、柱狀圖、網(wǎng)狀圖、蠟燭圖、雷達(dá)圖等都有XAxis對(duì)象

獲取X軸實(shí)例對(duì)象使用

XAxis xAxis = chart.getXAxis();

定制坐標(biāo)軸數(shù)據(jù)

  • setLabelRotationAngle(float angle): 設(shè)置X軸標(biāo)簽數(shù)據(jù)繪制的角度
  • setPosition(XAxisPosition pos): 設(shè)置標(biāo)簽數(shù)據(jù)繪制的位置,可以選擇以下的項(xiàng):TOP,BOTTOM,BOTH_SIDED,TOP_INSIDE or BOTTOM_INSIDE.

示例代碼

XAxis xAxis = chart.getXAxis();
xAxis.setPosition(XAxisPosition.BOTTOM);
xAxis.setTextSize(10f);
xAxis.setTextColor(Color.RED);
xAxis.setDrawAxisLine(true);
xAxis.setDrawGridLines(false);
// 設(shè)置定制的數(shù)據(jù)格式
xAxis.setValueFormatter(new MyCustomFormatter()); 




Y軸

任何與縱軸有關(guān)的數(shù)據(jù)信息都存放在Y軸中,像折線圖、柱狀圖、網(wǎng)狀圖、蠟燭圖等都有左右兩個(gè)YAxis對(duì)象,雷達(dá)圖只有一個(gè)YAxis對(duì)象

獲取YAxis實(shí)例對(duì)象

YAxis leftAxis = chart.getAxisLeft();
YAxis rightAxis = chart.getAxisRight();

YAxis leftAxis = chart.getAxis(AxisDependency.LEFT);

YAxis yAxis = radarChart.getYAxis(); // 雷達(dá)圖獲取YAxis方法

在運(yùn)行時(shí),可以使用public AxisDependency getAxisDependency()來(lái)確定YAxis是圖表的哪一邊的
想要設(shè)置效果必須在給圖表設(shè)置數(shù)據(jù)之前

Axis Dependency

默認(rèn)情況下,所有添加到圖表的數(shù)據(jù)都和左邊的Y軸數(shù)據(jù)相對(duì)應(yīng),沒(méi)有進(jìn)一步設(shè)置的情況下右邊的Y軸數(shù)據(jù)以及樣式比例均與左邊統(tǒng)一,如果你想要設(shè)置不同比例的Y軸,你可以通過(guò)設(shè)置對(duì)應(yīng)的數(shù)據(jù)來(lái)繪制對(duì)應(yīng)的坐標(biāo)軸實(shí)現(xiàn)

LineDataSet dataSet = ...; // 獲取dataset
dataSet.setAxisDependency(AxisDependency.RIGHT);

零線

除了網(wǎng)格線與YAxis上的每個(gè)值水平并排,還有所謂的零線,它在軸上的零(0)值處繪制,類似于網(wǎng)格線,但可以單獨(dú)配置。

  • setDrawZeroLine(boolean enabled): 是否繪制零線
  • setZeroLineWidth(float width): 設(shè)置零線寬度
  • setZeroLineColor(int color): 設(shè)置零線顏色

零線代碼示例:

// 數(shù)據(jù)設(shè)置在左邊坐標(biāo)軸
YAxis left = mChart.getAxisLeft();
left.setDrawLabels(false); // 不設(shè)置坐標(biāo)軸數(shù)據(jù)標(biāo)簽
left.setDrawAxisLine(false); // 不繪制坐標(biāo)軸線
left.setDrawGridLines(false); // 不繪制網(wǎng)格線
left.setDrawZeroLine(true); // 繪制零線
mChart.getAxisRight().setEnabled(false); // 不設(shè)置右邊Y軸
0line

沒(méi)有其他的線(坐標(biāo)軸線、網(wǎng)格線等等)只有一條零線的效果

更多的代碼示例:

YAxis yAxis = mChart.getAxisLeft();
yAxis.setTypeface(...); // 設(shè)置一個(gè)不同的字體
yAxis.setTextSize(12f); // 設(shè)置字體大小
yAxis.setAxisMinimum(0f); // 設(shè)置坐標(biāo)軸從0開(kāi)始
yAxis.setAxisMaximum(100f); // 設(shè)置坐標(biāo)軸最大值為100
yAxis.setTextColor(Color.BLACK); // 設(shè)置字體顏色為黑色
yAxis.setValueFormatter(new MyValueFormatter());
yAxis.setGranularity(1f); // 設(shè)置間隔為1
yAxis.setLabelCount(6, true); // 設(shè)置標(biāo)簽個(gè)數(shù)
//... 更多




設(shè)置數(shù)據(jù)

折線圖

如果想要給圖表添加數(shù)據(jù)需要使用以下方式:

public void setData(ChartData data) { ... }

基類CharData包含在渲染時(shí)圖表所需要的所有的數(shù)據(jù)和信息
對(duì)于每一種數(shù)據(jù)圖表,都有一個(gè)CharData的子類用于給圖表設(shè)置數(shù)據(jù)

在構(gòu)造函數(shù)中,可以使用List<? extends IDataSet>作為數(shù)據(jù)去顯示,

兩種不同的構(gòu)造函數(shù)

    /** List constructor */
    public LineData(List<ILineDataSet> sets) { ... }

    /** Constructor with one or multiple ILineDataSet objects */
    public LineData(ILineDataSet...) { ... }

一個(gè)DataSet對(duì)象代表一組圖表中一起的數(shù)據(jù),這樣可以在邏輯上分離圖表上的不同組數(shù)據(jù).
對(duì)于每種類型的圖表,存在允許特定樣式的擴(kuò)展DataSet的不同對(duì)象(例如Line DataSet)

舉個(gè)例子,如果你想要顯示兩家不同公司上一年季度性的財(cái)政收入,推薦使用兩個(gè)LineDataSet,每一個(gè)中包含四組數(shù)據(jù)
那么如何去設(shè)置LineDataSet對(duì)象呢

public LineDataSet(List<Entry> entries,String label){...}

可以看到,LineDataSet的構(gòu)造函數(shù)中需要List<Entry>一系列的數(shù)據(jù)以及用于描述數(shù)據(jù)信息的label,
此label還可以進(jìn)一步在LineData中去找到對(duì)應(yīng)的LineDataSet對(duì)象
這些Entry的列表中包含了圖表的所有數(shù)據(jù),而Entry類就相當(dāng)于X、Y坐標(biāo)值的一個(gè)包裝類,用于存放一個(gè)具體的坐標(biāo)值

public Entry(float x, float y) { ... }

上面的例子,我們第一步可以創(chuàng)建一個(gè)用于存放公司收入的Entry的集合

List<Entry> valsComp1 = new ArrayList<Entry>();
List<Entry> valsComp2 = new ArrayList<Entry>();

然后填充數(shù)據(jù),確保Entry內(nèi)的X軸數(shù)據(jù)是精確的

    Entry c1e1 = new Entry(0f, 100000f); // 一公司第一季度數(shù)據(jù)
    valsComp1.add(c1e1);
    Entry c1e2 = new Entry(1f, 140000f); // 一公司第二季度數(shù)據(jù)
    valsComp1.add(c1e2);
    // 繼續(xù)添加
    
    Entry c2e1 = new Entry(0f, 130000f); // 二公司第一季度數(shù)據(jù)
    valsComp2.add(c2e1);
    Entry c2e2 = new Entry(1f, 115000f); // 二公司第二季度數(shù)據(jù)
    valsComp2.add(c2e2);
    //...

現(xiàn)在我們可以通過(guò)這一系列數(shù)據(jù)去創(chuàng)建LineDataSet對(duì)象

    LineDataSet setComp1 = new LineDataSet(valsComp1, "Company 1");
    setComp1.setAxisDependency(AxisDependency.LEFT);
    LineDataSet setComp2 = new LineDataSet(valsComp2, "Company 2");
    setComp2.setAxisDependency(AxisDependency.LEFT);

通過(guò)使用setAxisDependency來(lái)指定具體數(shù)據(jù)繪制的軸,然后通過(guò)創(chuàng)建IDataSets的List來(lái)構(gòu)成ChartData對(duì)象

    // 使用ILineDataSet接口
    List<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
    dataSets.add(setComp1);
    dataSets.add(setComp2);
    
    LineData data = new LineData(dataSets);
    mLineChart.setData(data);
    mLineChart.invalidate(); // 刷新

在調(diào)用invalidate方法刷新后,數(shù)據(jù)就會(huì)被繪制出來(lái)

如果我們想特別定制X軸數(shù)據(jù)來(lái)替換原先的0到3,我們可以使用IAxisValueFormatter接口
這個(gè)接口可以讓我們自定義X軸數(shù)據(jù)顯示樣式
舉個(gè)例子,像以下這樣設(shè)置數(shù)據(jù)格式:

// 繪制在X軸上的數(shù)據(jù)數(shù)組
final String[] quarters = new String[] { "Q1", "Q2", "Q3", "Q4" };

IAxisValueFormatter formatter = new IAxisValueFormatter() {

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        return quarters[(int) value];
    }

    @Override
    public int getDecimalDigits() {  return 0; }
};

XAxis xAxis = mLineChart.getXAxis();
xAxis.setGranularity(1f); // 最小的間隔設(shè)置為1
xAxis.setValueFormatter(formatter);

最后渲染的圖表的樣子


Formatter

BarChart,ScatterChart,BubbleChart和CandleStickChart的設(shè)置數(shù)據(jù)與LineChart一樣
其中特殊的是BarChart將會(huì)在下面進(jìn)行解釋:

數(shù)據(jù)排序

如果List<Entry>沒(méi)有正確的X軸排列順序,可能導(dǎo)致一些意外的情況
我們可以使用EntryXComparator來(lái)進(jìn)行排序

List<Entry> entries = ...;
Collections.sort(entries, new EntryXComparator());

柱狀圖

柱狀圖的設(shè)置數(shù)據(jù)方式與折線圖類似,最大的不同在于柱狀圖存放數(shù)據(jù)的BarEntry有一些不同的樣式設(shè)置

創(chuàng)建BarDataSet

List<BarEntry> entries = new ArrayList<>();
entries.add(new BarEntry(0f, 30f));
entries.add(new BarEntry(1f, 80f));
entries.add(new BarEntry(2f, 60f));
entries.add(new BarEntry(3f, 50f)); 
                                    // 跳過(guò)第五個(gè)
entries.add(new BarEntry(5f, 70f));
entries.add(new BarEntry(6f, 60f));

BarDataSet set = new BarDataSet(entries, "BarDataSet");

將數(shù)據(jù)設(shè)置到圖表上

BarData data = new BarData(set);
data.setBarWidth(0.9f); // 設(shè)置數(shù)據(jù)條的寬度
chart.setData(data);
chart.setFitBars(true); // 讓X軸與所有的數(shù)據(jù)條適配
chart.invalidate(); // 刷新

當(dāng)柱狀圖被創(chuàng)建時(shí),每一個(gè)條都有1f的寬度,設(shè)置為0.9f的寬度后,將會(huì)在兩個(gè)條各存在0.1f的間隔
設(shè)置setFitBars(true)將會(huì)讓X軸的范圍很好的適配柱狀圖,而不會(huì)出現(xiàn)有哪個(gè)條被邊緣線切斷

刷新后顯示:


barChart

群組柱狀圖

YourData[] group1 = ...;
YourData[] group2 = ...;

List<BarEntry> entriesGroup1 = new ArrayList<>();
List<BarEntry> entriesGroup2 = new ArrayList<>();

// 填充數(shù)據(jù)
for(int i = 0; i < group1.length; i++) {
    entriesGroup1.add(new BarEntry(i, group1.getValue()));
    entriesGroup2.add(new BarEntry(i, group2.getValue()));
}

//兩組數(shù)據(jù)
BarDataSet set1 = new BarDataSet(entriesGroup1, "Group 1");
BarDataSet set2 = new BarDataSet(entriesGroup2, "Group 2");

這樣就獲取到兩組數(shù)據(jù),現(xiàn)在用這兩組數(shù)據(jù)去完成群組柱狀圖

float groupSpace = 0.06f; //群組間的間隔
float barSpace = 0.02f; // 每一個(gè)柱狀條間隔
float barWidth = 0.45f; // 每一個(gè)柱狀條的寬度
// (0.02 + 0.45) * 2 + 0.06 = 1.00 -> 總共合起來(lái)還是1f

BarData data = new BarData(set1, set2); //設(shè)置組數(shù)據(jù)
data.setBarWidth(barWidth); // 設(shè)置柱狀條寬度
barChart.setData(data);
barChart.groupBars(1980f, groupSpace, barSpace); // 設(shè)置組樣式寬度等
barChart.invalidate(); // 刷新

groupBars(...)對(duì)群組數(shù)據(jù)進(jìn)行了具體的設(shè)置,這個(gè)方法的具體參數(shù)

public void groupBars(float fromX, float groupSpace, float barSpace) { ... }

fromX標(biāo)識(shí)X軸數(shù)據(jù)從哪邊開(kāi)始進(jìn)行渲染

最后渲染出來(lái)為:


group_bar_chart

通過(guò)使用setCenterAxisLabels(...)方法可以讓標(biāo)簽數(shù)據(jù)正確顯示在群組柱狀條中間

XAxis xAxis = chart.getXAxis();
xAxis.setCenterAxisLabels(true);

疊加柱狀圖

設(shè)置與普通的柱狀圖類似,不同的是BarEntry的構(gòu)造函數(shù)使用

public BarEntry(float x, float [] yValues) { ... }

第二個(gè)參數(shù)是一個(gè)疊加的數(shù)據(jù)值數(shù)組

BarEntry stackedEntry = new BarEntry(0f, new float[] { 10, 20, 30 });

這樣在圖表上顯示高度為10,20,30的三段數(shù)據(jù)

餅圖

不同于其他的圖形,餅圖的構(gòu)造函數(shù)是這樣的:

public PieEntry(float value, String label) { ... }

第一個(gè)參數(shù)即是當(dāng)前所占區(qū)域的大小數(shù)據(jù),第二個(gè)參數(shù)用于描述當(dāng)前區(qū)域的信息

完整的餅圖的創(chuàng)建

List<PieEntry> entries = new ArrayList<>();

entries.add(new PieEntry(18.5f, "Green"));
entries.add(new PieEntry(26.7f, "Yellow"));
entries.add(new PieEntry(24.0f, "Red"));
entries.add(new PieEntry(30.8f, "Blue"));

PieDataSet set = new PieDataSet(entries, "Election Results");
PieData data = new PieData(set);
pieChart.setData(data);
pieChart.invalidate(); // 刷新

餅圖沒(méi)有X軸,數(shù)據(jù)的顯示順序由添加順序來(lái)定義
渲染完成后:


pie_chart




設(shè)置顏色

在這個(gè)小例子中我們有兩組數(shù)據(jù)用于代表兩個(gè)公司季度收入,我們想要設(shè)置不同的顏色去區(qū)分它們
我們想要:

  • Company1使用四種不同的紅色去標(biāo)注四個(gè)不同的季度數(shù)據(jù)
  • Company2使用四種不同的綠色去標(biāo)注四個(gè)不同的季度數(shù)據(jù)
  LineDataSet setComp1 = new LineDataSet(valsComp1, "Company 1");
  setComp1.setColors(new int[] { R.color.red1, R.color.red2, R.color.red3, R.color.red4 }, Context);
  
  LineDataSet setComp2 = new LineDataSet(valsComp2, "Company 2");
  setComp2.setColors(new int[] { R.color.green1, R.color.green2, R.color.green3, R.color.green4 }, Context);

給DataSet設(shè)置顏色的方法

  • setColors(int [] colors, Context c): 通過(guò)使用 new Int[]{R.color.red,...}的形式給dataset提供顏色數(shù)據(jù)
  • setColors(int [] colors):通過(guò)使用 new Int[]{R.color.red,...}的形式給dataset提供顏色數(shù)據(jù),必須確保在調(diào)用之前顏色都是可用的
  • setColors(ArrayList<Integer> colors): 提供List類型的顏色集合,必須確保在調(diào)用之前顏色都是可用的
  • setColor(int color): 設(shè)置單一的顏色,在內(nèi)部還是創(chuàng)建數(shù)組并添加這個(gè)顏色

當(dāng)然也可以使用顏色模板

LineDataSet set = new LineDataSet(...);
set.setColors(ColorTemplate.VORDIPLOM_COLORS);

在沒(méi)有設(shè)置顏色的時(shí)候,將會(huì)使用默認(rèn)的顏色




ValueFormatter接口

IValueFormatter接口用于創(chuàng)建自定義格式類來(lái)在圖表繪制之前格式數(shù)據(jù)
使用IValueFormatter,簡(jiǎn)單的創(chuàng)建一個(gè)類去實(shí)現(xiàn)這個(gè)接口,并返回你從getFormattedValue(...)方法獲取的數(shù)據(jù)想要顯示的樣子

創(chuàng)建一個(gè)格式化類

public class MyValueFormatter implements IValueFormatter {

    private DecimalFormat mFormat;
    
    public MyValueFormatter() {
        mFormat = new DecimalFormat("###,###,##0.0"); // 使用金融類型的格式
    }
    
    @Override
    public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
        // 寫下你的代碼邏輯
        return mFormat.format(value) + " $"; // 比如在數(shù)據(jù)前添加一個(gè)$符
    }
}

給ChartData或者DataSet添加格式化

// 圖表內(nèi)的數(shù)據(jù)均使用這種格式
lineData.setValueFormatter(new MyValueFormatter());

// 僅在該DataSet內(nèi)使用這種格式
lineDataSet.setValueFormatter(new MyValueFormatter());

預(yù)置格式類

  • LargeValueFormatter: 用于格式化大數(shù)據(jù) 超過(guò)"1,000"的值將會(huì)被格式化為"1K",超過(guò)"1,000,000"將會(huì)變成"1M",超過(guò)"1,000,000,000"將會(huì)變成"1M",并且像one trillion這樣的數(shù)據(jù)將會(huì)被格式成"1t".
  • PercentFormatter: 使用百分比修飾數(shù)據(jù)在餅圖中很有用. 50 -> 50.0 %
  • StackedValueFormatter: 用于層疊柱狀圖中,用于格式數(shù)據(jù)是否是顯示多層數(shù)據(jù)還是僅僅只顯示最頂部的數(shù)據(jù)




AxisValueFormatter接口

創(chuàng)建一個(gè)格式化類

創(chuàng)建一個(gè)類實(shí)現(xiàn)IAxisValueFormatter接口,用于格式化坐標(biāo)軸上的值

public class MyYAxisValueFormatter implements IAxisValueFormatter {

    private DecimalFormat mFormat;

    public MyAxisValueFormatter() {
        //格式化數(shù)字
        mFormat = new DecimalFormat("###,###,##0.0");
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // value參數(shù)標(biāo)識(shí)在坐標(biāo)軸上的位置或者說(shuō)是數(shù)據(jù)值,axis標(biāo)識(shí)是哪個(gè)坐標(biāo)軸
        return mFormat.format(value) + " $";
    }
    
    /** 只有為數(shù)字時(shí)返回 其余返回0*/
    @Override
    public int getDecimalDigits() { return 1; }
}

下面的例子展示怎么把數(shù)組中的數(shù)據(jù)展示到坐標(biāo)軸上去

public class MyXAxisValueFormatter implements IAxisValueFormatter {

    private String[] mValues;

    public MyXAxisValueFormatter(String[] values) {
        this.mValues = values;
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        return mValues[(int) value];
    }
    
    @Override
    public int getDecimalDigits() { return 0; }
}

設(shè)置格式化類

在創(chuàng)建好格式化類之后,簡(jiǎn)單去運(yùn)用它

YAxis left = chart.getAxisLeft();
left.setValueFormatter(new MyYAxisValueFormatter());
String[] values = new String[] { ... };
XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new MyXAxisValueFormatter(values));

設(shè)置完之后,圖表用格式化類來(lái)具體指定值來(lái)代替默認(rèn)的坐標(biāo)軸的最小值和最大值范圍

限制間隔

如果使用上面的數(shù)組格式化坐標(biāo)軸標(biāo)簽值,可以使用一下的代碼去限制標(biāo)簽間的間隔

axis.setGranularity(1f);

這將可以預(yù)防坐標(biāo)軸繪制重疊的數(shù)據(jù),因?yàn)樵诳s放到一定的程度時(shí),圖表將會(huì)停止計(jì)算更小的標(biāo)簽范圍

預(yù)置格式化類

  • LargeValueFormatter: 用于格式化大數(shù)據(jù) 超過(guò)"1,000"的值將會(huì)被格式化為"1K",超過(guò)"1,000,000"將會(huì)變成"1M",超過(guò)"1,000,000,000"將會(huì)變成"1M",并且像one trillion這樣的數(shù)據(jù)將會(huì)被格式成"1t".
  • PercentFormatter: 使用百分比修飾數(shù)據(jù)在餅圖中很有用. 50 -> 50.0 %




通用的圖表和樣式設(shè)置

刷新

  • invalidate(): 使用這個(gè)方法刷新圖表將會(huì)重新繪制,更改圖表后想要生效必須調(diào)用
  • notifyDataSetChanged(): 讓圖表知道依賴的數(shù)據(jù)發(fā)生變化時(shí)調(diào)用,調(diào)用后圖表會(huì)重新計(jì)算,在使用動(dòng)態(tài)數(shù)據(jù)時(shí)很有用

日志

  • setLogEnabled(boolean enabled): 設(shè)置為true時(shí)將會(huì)打印日志信息,但是打開(kāi)將會(huì)影響性能所以不是必要的話請(qǐng)關(guān)閉

大體的樣式設(shè)置

下面是一些可以直接在Chart上使用的樣式設(shè)置方法

  • setBackgroundColor(int color): 設(shè)置整個(gè)圖表的背景顏色,也可以在.xml布局文件中進(jìn)行設(shè)置
  • setDescription(String desc): 在圖表的右下角設(shè)置一個(gè)圖表描述標(biāo)注
  • setDescriptionColor(int color): 設(shè)置圖表描述的字體顏色
  • setDescriptionPosition(float x, float y): 設(shè)置圖表描述的顯示位置
  • setDescriptionTypeface(Typeface t): 設(shè)置圖表描述的字體樣式
  • setDescriptionTextSize(float size): 設(shè)置圖表描述的字體大小,通過(guò)像素值設(shè)置或者使用min(6f)、max(16f)
  • setNoDataText(String text): 如果圖表沒(méi)有數(shù)據(jù)時(shí)顯示的標(biāo)注
  • setDrawGridBackground(boolean enabled): 如果開(kāi)啟的話,圖表繪制區(qū)域背后的矩形區(qū)域?qū)?huì)被繪制
  • setGridBackgroundColor(int color): 設(shè)置背景矩形的顏色
  • setDrawBorders(boolean enabled): 設(shè)置是否繪制圖表邊框
  • setBorderColor(int color): 設(shè)置邊框顏色
  • setBorderWidth(float width): 設(shè)置邊框線寬,單位為dp
  • setMaxVisibleValueCount(int count): 設(shè)置圖表可見(jiàn)數(shù)據(jù)標(biāo)簽的最大個(gè)數(shù),只有當(dāng)setDrawValues()開(kāi)啟時(shí)生效




具體的圖表和樣式設(shè)置

Line-, Bar-, Scatter-, Candle- & BubbleChart

  • setAutoScaleMinMaxEnabled(boolean enabled): 根據(jù)最大最小數(shù)據(jù)值圖表進(jìn)行自動(dòng)縮放,在展示金融類型的數(shù)據(jù)時(shí)很有趣,默認(rèn)關(guān)閉
  • setKeepPositionOnRotation(boolean enabled): 設(shè)置在轉(zhuǎn)變方向時(shí)(橫屏豎屏),圖表的縮放滾動(dòng)不發(fā)生改變,默認(rèn)關(guān)閉

BarChart

  • setDrawValueAboveBar(boolean enabled): 設(shè)置為true時(shí),數(shù)據(jù)將會(huì)被渲染在數(shù)據(jù)條上方,而不是在頂部的下方顯示
  • setDrawBarShadow(boolean enabled): 設(shè)置為true時(shí),將會(huì)在數(shù)據(jù)條背后根據(jù)最大值繪制陰影,但是開(kāi)啟將會(huì)降低大概40%的性能
  • setDrawValuesForWholeStack(boolean enabled): 如果設(shè)置為true,堆疊條的所有值都會(huì)單獨(dú)繪制,而不僅僅是繪制它們的總和。
  • setDrawHighlightArrow(boolean enabled): 設(shè)置為true時(shí)將會(huì)在數(shù)據(jù)高亮?xí)r,在數(shù)據(jù)條上方高亮繪制箭頭

PieChart

  • setDrawSliceText(boolean enabled): 設(shè)置為true,將會(huì)在餅圖片內(nèi)繪制文字
  • setUsePercentValues(boolean enabled): 當(dāng)開(kāi)啟時(shí),將不會(huì)使用原來(lái)的數(shù)據(jù)值,而是百分比格式過(guò)得到的百分比數(shù)據(jù)
  • setCenterText(SpannableString text): 設(shè)置為true時(shí)文字將會(huì)在圖表中間繪制,過(guò)長(zhǎng)的文字將會(huì)被自動(dòng)縮略以免繪制到餅圖片上
  • setCenterTextRadiusPercent(float percent): 設(shè)置中心文本邊界框的矩形半徑,作為餅圖孔的百分比,默認(rèn)值1.f(100%)
  • setHoleRadius(float percent): 以最大半徑的百分比(最大半徑=整個(gè)圖表的半徑)來(lái)設(shè)置餅圖中心的孔半徑,默認(rèn)為50%
  • setTransparentCircleRadius(float percent): 設(shè)置餅圖中孔旁邊的透明圓的半徑,以最大半徑的百分比表示(最大半徑=整個(gè)圖表的半徑),默認(rèn)為55%->默認(rèn)情況下比中心孔大5%
  • setTransparentCircleColor(int color): 設(shè)置透明圓的顏色
  • setTransparentCircleAlpha(int alpha): 設(shè)置透明圓的透明度
  • setMaxAngle(float maxangle): 設(shè)置餅圖的角度. 360f意味著是一個(gè)整圓的餅圖,180f就是一個(gè)半圓的餅圖.默認(rèn)值360f

RadarChart

  • setSkipWebLineCount(int count): 允許跳過(guò)繪制來(lái)自圖表中心的網(wǎng)絡(luò)線,在線特別多的情況下很有用




圖例

圖例通常有一個(gè)標(biāo)識(shí)和一字符串組成,標(biāo)識(shí)為代表該數(shù)據(jù)的DataSet的顏色決定,字符串是DataSet的描述

獲取圖例對(duì)象

Legend legend = chart.getLegend();
  • setEnabled(boolean enabled): 設(shè)置圖例是否被繪制

設(shè)置圖例的樣式

  • setTextColor(int color): 設(shè)置圖例上的字體顏色
  • setTextSize(float size): 設(shè)置圖例字體大小
  • setTypeface(Typeface tf): 設(shè)置圖例字體

大小

  • setWordWrapEnabled(boolean enabled): 如果啟用,圖例的內(nèi)容將不會(huì)剪切到圖表邊界外,而是創(chuàng)建一個(gè)新的線條即換行.請(qǐng)注意,這會(huì)降低性能,僅適用于圖表下面的圖例
  • setMaxSizePercent(float maxSize): 設(shè)置圖表相對(duì)于View的最大相對(duì)大小,默認(rèn)為0.95即95%

自定義圖例

  • setPosition(LegendPosition pos): 設(shè)置圖例要顯示的位置. 可以設(shè)置這些值:RIGHT_OF_CHART,RIGHT_OF_CHART_CENTER,RIGHT_OF_CHART_INSIDE,BELOW_CHART_LEFT,BELOW_CHART_RIGHT,BELOW_CHART_CENTER or PIECHART_CENTER(只有餅圖有)等等更多
  • setForm(LegendForm shape): 設(shè)置圖例顯示的樣式可以選擇SQUARE(方形圖例),CIRCLE(圓形圖例) or LINE(線型圖例).
  • setFormSize(float size): 設(shè)置圖例大小
  • setXEntrySpace(float space): 設(shè)置如果在X軸上的圖例的間距
  • setYEntrySpace(float space): 設(shè)置如果在Y軸上的圖例的間距
  • setFormToTextSpace(float space): 設(shè)置圖例上圖示和文字之間的間距

設(shè)置自定義的標(biāo)簽

  • setCustom(int[] colors, String[] labels): 自定義標(biāo)簽顏色和文字內(nèi)容,兩個(gè)數(shù)組的大小必須相等
  • resetCustom():將會(huì)重置圖例標(biāo)簽,根據(jù)默認(rèn)的自動(dòng)計(jì)算得到默認(rèn)的圖例標(biāo)簽
  • setExtra(int[] colors, String[] labels): 給默認(rèn)顯示的圖例增加新的內(nèi)容,如果默認(rèn)內(nèi)容已經(jīng)計(jì)算完畢,需要調(diào)用notifyDataSetChanged()來(lái)生效

例子

    Legend l = chart.getLegend();
    l.setFormSize(10f); 
    l.setForm(LegendForm.CIRCLE); 
    l.setPosition(LegendPosition.BELOW_CHART_LEFT);
    l.setTypeface(...);
    l.setTextSize(12f);
    l.setTextColor(Color.BLACK);
    l.setXEntrySpace(5f); 
    l.setYEntrySpace(5f); 

    l.setCustom(ColorTemplate.VORDIPLOM_COLORS, new String[] { "Set1", "Set2", "Set3", "Set4", "Set5" });

    // and many more...




動(dòng)態(tài)實(shí)時(shí)數(shù)據(jù)

MPAndroidChart并不支持實(shí)時(shí)數(shù)據(jù),但是為了向圖表添加新數(shù)據(jù)或動(dòng)態(tài)刪除數(shù)據(jù),有各種方法可以將Entry對(duì)象添加到已有的DataSet對(duì)象或從已有的ChartData對(duì)象中刪除DataSet對(duì)象

動(dòng)態(tài)添加刪除數(shù)據(jù)

Class DataSet(以及所有子類):

  • addEntry(Entry e): 向DataSet中添加一個(gè)Entry對(duì)象

Class ChartData(以及所有子類):

  • addEntry(Entry e, int dataSetIndex): 將Entry對(duì)象添加到內(nèi)部的某一個(gè)DataSet(由dataSetIndex決定)中去
  • addDataSet(DataSet d): 添加一個(gè)DataSet到ChartData中去

同樣也有刪除數(shù)據(jù)的方法

Class DataSet(以及所有子類):

  • public boolean removeFirst(): 刪除內(nèi)部的第一個(gè)Entry對(duì),刪除成功返回true,失敗返回false
  • public boolean removeLast(): 刪除內(nèi)部的最后一個(gè)Entry對(duì),刪除成功返回true,失敗返回false
  • public boolean removeEntry(Entry e): 刪除指定的一個(gè)Entry對(duì)(傳入這個(gè)Entry對(duì)象),刪除成功返回true,失敗返回false
  • public boolean removeEntry(int xIndex): 刪除指定的一個(gè)Entry對(duì)(傳入這個(gè)Entry對(duì)象的位置索引),刪除成功返回true,失敗返回false

Class ChartData(以及所有子類):

  • public boolean removeEntry(Entry e, int dataSetIndex): 刪除內(nèi)部某一個(gè)DataSet(由dataSetIndex決定)的第一個(gè)Entry對(duì),刪除成功返回true,失敗返回false
  • public boolean removeEntry(int xIndex, int dataSetIndex): 刪除內(nèi)部某一個(gè)DataSet(由dataSetIndex決定)的一個(gè)Entry對(duì)(傳入這個(gè)Entry對(duì)象的位置索引),刪除成功返回true,失敗返回false
  • public boolean removeDataSet(DataSet d): 刪除指定的一個(gè)dataSet(傳入這個(gè)dataSet對(duì)象),刪除成功返回true,失敗返回false
  • public boolean removeDataSet(int index): 刪除指定的一個(gè)dataSet(傳入這個(gè)dataSet對(duì)象位置索引),刪除成功返回true,失敗返回false

一定要記住

在動(dòng)態(tài)刪除或者添加數(shù)據(jù)之后,一定要在調(diào)用invalidate()刷新頁(yè)面之前調(diào)用notifyDataSetChanged()方法更新數(shù)據(jù)

 // EXAMPLE 1
 // add entries to the "data" object
 exampleData.addEntry(...);
 chart.notifyDataSetChanged(); // 讓Chart知道數(shù)據(jù)發(fā)生變化
 chart.invalidate(); // 刷新

 // EXAMPLE 2
 // add entries to "dataSet" object
 dataSet.addEntry(...);
 exampleData.notifyDataChanged(); // 讓DataSet知道數(shù)據(jù)發(fā)生變化
 chart.notifyDataSetChanged(); // 讓Chart知道數(shù)據(jù)發(fā)生變化
 chart.invalidate(); // 刷新




調(diào)整視窗顯示

這些方法只適用于LineChart,BarChart,ScatterChart和CandleStickChart

規(guī)定哪些可以顯示

  • setVisibleXRangeMaximum(float maxXRange): 設(shè)置視窗X軸顯示的范圍最大值,如果設(shè)置為10,那么超過(guò)10個(gè)數(shù)據(jù)的值在不滾動(dòng)的情況下將不會(huì)顯示
  • setVisibleXRangeMinimum(float minXRange): 設(shè)置視窗X軸顯示的范圍最小值,如果設(shè)置為10,那么在縮放的時(shí)候始終將有10個(gè)數(shù)據(jù)顯示在圖表上
  • setVisibleYRangeMaximum(float maxYRange, AxisDependency axis): 設(shè)置視窗Y軸顯示的范圍最大值,如果設(shè)置為10,那么超過(guò)10個(gè)數(shù)據(jù)的值在不滾動(dòng)的情況下將不會(huì)顯示,設(shè)置存在在哪一邊的Y軸
  • setViewPortOffsets(float left, float top, float right, float bottom): 為當(dāng)前ViewPort設(shè)置自定義偏移量(實(shí)際圖表窗口兩側(cè)的偏移量),設(shè)置這將阻止圖表自動(dòng)計(jì)算偏移量, 使用resetViewPortOffsets()來(lái)取消這個(gè). 只有當(dāng)你知道你在做什么時(shí)才使用這個(gè)方法
  • resetViewPortOffsets(): 重置自定義偏移量,重新讓圖表自己進(jìn)行計(jì)算
  • setExtraOffsets(float left, float top, float right, float bottom): 在自動(dòng)計(jì)算的偏移量基礎(chǔ)上再加上額外的偏移量,但這個(gè)偏移量不會(huì)影響自動(dòng)計(jì)算出來(lái)的

移動(dòng)View

  • fitScreen(): 重置所有的移動(dòng)和縮放,并讓圖表完全適配它的邊界(完全縮小).
  • moveViewToX(float xValue): 將當(dāng)前視窗的左側(cè)(邊緣)移動(dòng)到指定的x值。.
  • moveViewToY(float yValue, AxisDependency axis): 將根據(jù)左邊或者右邊Y軸選中的數(shù)據(jù)使視窗將該值處于視窗中間
  • moveViewTo(float xValue, float yValue, AxisDependency axis): 上面兩個(gè)方法的集合,就是將視窗焦點(diǎn)聚集到選中的某一點(diǎn)(視窗左邊線在點(diǎn)上)
  • centerViewTo(float xValue, float yValue, AxisDependency axis): 上面兩個(gè)方法的集合,就是將視窗焦點(diǎn)聚集到選中的某一點(diǎn)(視窗中心線在點(diǎn)上)

使用動(dòng)畫移動(dòng)View

  • moveViewToAnimated(float xValue, float yValue, AxisDependency axis, long duration): 使用動(dòng)畫效果將左邊緣移至所要到的點(diǎn)
  • centerViewToAnimated(float xValue, float yValue, AxisDependency axis, long duration): 使用動(dòng)畫效果將中心移至所要到的點(diǎn)

所有的moveViewTo類似的方法都會(huì)自動(dòng)調(diào)用invalidate方法去刷新頁(yè)面,不需要手動(dòng)去調(diào)用

縮放(以代碼方式)

  • zoomIn(): 以1.4f的縮放比系數(shù)放大視圖中心焦點(diǎn)
  • zoomOut(): 從視圖中心焦點(diǎn)以0.7f的縮放比系數(shù)縮小視圖
  • zoom(float scaleX, float scaleY, float x, float y): 自定義縮放比,自定義縮放中心,記住 1f縮放值等于沒(méi)有縮放 0到1之間為縮小操作,1以上為放大操作
  • zoom(float scaleX, float scaleY, float xValue, float yValue, AxisDependency axis): 和上面的方法一樣,增加了指定哪一邊的Y軸

縮放動(dòng)畫

  • zoomAndCenterAnimated(float scaleX, float scaleY, float xValue, float yValue, AxisDependency axis, long duration):使用動(dòng)畫進(jìn)行具體縮放比的縮放操作

例子:

chart.setData(...);

// 開(kāi)始設(shè)置視窗
chart.setVisibleXRangeMaximum(20); 
chart.moveViewToX(10);




動(dòng)畫

所有的圖表都提供了動(dòng)畫以供操作使用

有三種不同的動(dòng)畫存在

  • animateX(int durationMillis): 橫向變換時(shí)的動(dòng)畫,設(shè)置動(dòng)畫時(shí)長(zhǎng)
  • animateY(int durationMillis): 縱向變換時(shí)的動(dòng)畫,設(shè)置動(dòng)畫時(shí)長(zhǎng)
  • animateXY(int xDuration, int yDuration): 橫向縱向動(dòng)畫合集,分別設(shè)置動(dòng)畫時(shí)長(zhǎng)
mChart.animateX(3000); // animate horizontal 3000 milliseconds

mChart.animateY(3000); // animate vertical 3000 milliseconds

mChart.animateXY(3000, 3000); // animate horizontal and vertical 3000 milliseconds

平緩動(dòng)畫效果

你可以從Easing.EasingOption中選擇想要的預(yù)置平緩動(dòng)畫效果

public enum EasingOption {
      Linear,
      EaseInQuad,
      EaseOutQuad,
      EaseInOutQuad,
      EaseInCubic,
      EaseOutCubic,
      EaseInOutCubic,
      EaseInQuart,
      EaseOutQuart,
      EaseInOutQuart,
      EaseInSine,
      EaseOutSine,
      EaseInOutSine,
      EaseInExpo,
      EaseOutExpo,
      EaseInOutExpo,
      EaseInCirc,
      EaseOutCirc,
      EaseInOutCirc,
      EaseInElastic,
      EaseOutElastic,
      EaseInOutElastic,
      EaseInBack,
      EaseOutBack,
      EaseInOutBack,
      EaseInBounce,
      EaseOutBounce,
      EaseInOutBounce,
}

有兩種設(shè)置平緩動(dòng)畫效果的方法

  • 直接使用預(yù)設(shè)(所有Android版本均可使用)
public void animateY(int durationmillis, Easing.EasingOption option);

例如調(diào)用時(shí)就將動(dòng)畫效果設(shè)置進(jìn)去

mChart.animateY(3000, Easing.EasingOption.EaseOutBack); 
  • 自定義平滑效果(僅支持Android3.0以上版本)
public void animateY(int durationmillis, EasingFunction function); 

創(chuàng)建一個(gè)類去實(shí)現(xiàn)EasingFunction接口,在該類中實(shí)現(xiàn)自己的邏輯

/**
 * Interface for creating custom made easing functions. 
 */
 public interface EasingFunction {
    /**
     * Called everytime the animation is updated.
     * @param input - the time passed since the animation started (value between 0 and 1)
     */
     public float getInterpolation(float input);
 }

調(diào)用的時(shí)候(在Android3.0以下的版本中將會(huì)Crash掉)

mChart.animateY(3000, new MyEasingFunction()); 




IMarker接口(圖表數(shù)據(jù)標(biāo)注接口)

IMarker接口是你能夠在創(chuàng)建自定義的標(biāo)注樣式去顯示你圖表中高亮的數(shù)據(jù)
IMarker定義的像這樣:

public interface IMarker {

    /**
     * @return The desired (general) offset you wish the IMarker to have on the x- and y-axis.
     *         By returning x: -(width / 2) you will center the IMarker horizontally.
     *         By returning y: -(height / 2) you will center the IMarker vertically.
     */
    MPPointF getOffset();

    /**
     * @return The offset for drawing at the specific `point`. This allows conditional adjusting of the Marker position.
     *         If you have no adjustments to make, return getOffset().
     *
     * @param posX This is the X position at which the marker wants to be drawn.
     *             You can adjust the offset conditionally based on this argument.
     * @param posY This is the X position at which the marker wants to be drawn.
     *             You can adjust the offset conditionally based on this argument.
     */
    MPPointF getOffsetForDrawingAtPos(float posX, float posY);

    /**
     * 刷新方法
     *
     * @param e         The Entry the IMarker belongs to. This can also be any subclass of Entry, like BarEntry or
     *                  CandleEntry, simply cast it at runtime.
     * @param highlight The highlight object contains information about the highlighted value such as it's dataset-index, the
     *                  selected range or stack-index (only stacked bar entries).
     */
    void refreshContent(Entry e, Highlight highlight);

    /**
     * 使用傳遞來(lái)的Canvas對(duì)象在指定位置繪制對(duì)應(yīng)的標(biāo)注
     *
     * @param canvas
     * @param posX
     * @param posY
     */
    void draw(Canvas canvas, float posX, float posY);
}

創(chuàng)建一個(gè)標(biāo)注View

你需要?jiǎng)?chuàng)建一個(gè)類去實(shí)現(xiàn)IMarker接口

public class YourMarkerView implements IMarker { ... }

根據(jù)你自己的需要去實(shí)現(xiàn)你所要實(shí)現(xiàn)的方法

下面例子的這種方法更簡(jiǎn)單,不需要實(shí)現(xiàn)IMarker接口提供的所有方法
只有特定的方法可以被覆蓋和定制,最重要的是重寫refreshContent方法來(lái)調(diào)整由標(biāo)記繪制的數(shù)據(jù)

public class YourMarkerView extends MarkerView {

    private TextView tvContent;

    public MyMarkerView(Context context, int layoutResource) {
        super(context, layoutResource);

        // find your layout components
        tvContent = (TextView) findViewById(R.id.tvContent);
    }

    // callbacks everytime the MarkerView is redrawn, can be used to update the
    // content (user-interface)
    @Override
    public void refreshContent(Entry e, Highlight highlight) {

        tvContent.setText("" + e.getY());

        // this will perform necessary layouting
        super.refreshContent(e, highlight);
    }

    private MPPointF mOffset; 

    @Override
    public MPPointF getOffset() {

        if(mOffset == null) {
           // center the marker horizontally and vertically
           mOffset = new MPPointF(-(getWidth() / 2), -getHeight());
        }

        return mOffset;
    }
}

獲取和設(shè)置標(biāo)注對(duì)象

想要在圖表中使用你設(shè)置好的marker,使用setMarker方法

IMarker marker = new YourMarkerView();
chart.setMarker(marker);

獲取一個(gè)已經(jīng)存在的marker,使用getMarker()方法

IMarker marker = chart.getMarker();

預(yù)置的標(biāo)注

  • MarkerView: 允許加載一個(gè)layout去展示對(duì)應(yīng)的標(biāo)注,繼承這個(gè)類并重寫refreshContent(...)方法來(lái)使用標(biāo)注數(shù)據(jù)
  • MarkerImage: 允許加載一張圖片在標(biāo)注上顯示對(duì)應(yīng)的圖片,繼承這個(gè)類并重寫refreshContent(...)方法來(lái)使用標(biāo)注數(shù)據(jù)




ChartData類 圖表數(shù)據(jù)類

ChartData類是所有圖表數(shù)據(jù)類的基類

public class LineData extends ChartData { ...

下面的是已經(jīng)被實(shí)現(xiàn)且在子類中可以使用的方法

數(shù)據(jù)樣式

  • setValueTextColor(int color): 設(shè)置數(shù)據(jù)顏色
  • setValueTextColors(List colors): 設(shè)置數(shù)據(jù)顏色(傳入顏色數(shù)組)
  • setValueTextSize(float size): 設(shè)置數(shù)據(jù)字體大小
  • setValueTypeface(Typeface tf): 設(shè)置數(shù)據(jù)字體
  • setValueFormatter(ValueFormatter f): 設(shè)置數(shù)據(jù)格式化類
  • setDrawValues(boolean enabled): 控制是否繪制數(shù)據(jù)值

獲取數(shù)據(jù)

  • getDataSetByIndex(int index): 根據(jù)索引值獲取DataSet
  • contains(Entry entry): 查看是否包含某個(gè)具體的Entry對(duì),對(duì)性能損耗嚴(yán)重
  • contains(T dataSet): 查看是否包含某個(gè)DataSet

清空數(shù)據(jù)

  • clearValues(): 清除所DataSet數(shù)據(jù)和依賴的Entry對(duì)數(shù)據(jù),但不會(huì)刪除X軸上的坐標(biāo)軸數(shù)據(jù)

高亮

  • setHighlightEnabled(boolean enabled): 設(shè)置是否允許高亮.
  • setDrawVerticalHighlightIndicator(boolean enabled): 是否繪制縱向高亮指示線
  • setDrawHorizontalHighlightIndicator(boolean enabled): 是否繪制橫向高亮指示線

動(dòng)態(tài)數(shù)據(jù)

  • notifyDataChanged(): 讓數(shù)據(jù)類知道數(shù)據(jù)發(fā)生了變化

ChartData的子類

BarData

  • setGroupSpace(float percent): 設(shè)置一組數(shù)據(jù)間的間距.100是一個(gè)數(shù)據(jù)條的長(zhǎng)度,默認(rèn)80
  • isGrouped(): 判斷該柱狀圖是不是群組柱狀圖

ScatterData

  • getGreatestShapeSize(): 通過(guò)內(nèi)部的數(shù)據(jù)查詢最大的Shape值.

PieData

  • getDataSet(): 獲取DataSet,PieData不能擁有多個(gè)DataSet
  • setDataSet(PieDataSet set): 設(shè)置DataSet

BubbleData

  • setHighlightCircleWidth(float width): 設(shè)置高亮圈寬度




DataSet數(shù)據(jù)類

DataSet數(shù)據(jù)類用法與ChartData幾乎一模一樣

子類

Line-, Bar-, Scatter-, Bubble- & CandleDataSet

  • setHighLightColor(int color): 設(shè)置高亮顏色

Line-, Bar-, Scatter-, Candle- & RadarDataSet

  • setDrawHighlightIndicators(boolean enabled): 控制是否繪制高亮指示線
  • setHighlightLineWidth(float width): 設(shè)置高亮指示線寬度

Line- & RadarDataSet

  • setFillColor(int color): 設(shè)置填充顏色
  • setFillAlpha(int alpha): 設(shè)置填充透明度
  • setFillDrawable(Drawable d): 選擇一個(gè)Drawable去填充
  • setDrawFilled(boolean filled): 開(kāi)啟之后將會(huì)完全填充繪制,而不是僅僅只有一條線,關(guān)閉這項(xiàng)將有性能上的提升,小于Android4.3無(wú)法使用,默認(rèn)關(guān)閉
  • setLineWidth(float width): 設(shè)置數(shù)據(jù)線寬度

LineDataSet

  • setCircleRadius(float size): 設(shè)置圓形指示器的圓弧度,默認(rèn)值4f
  • setDrawCircles(boolean enabled):設(shè)置是否繪制圓形指示器,默認(rèn)true
  • setDrawCubic(boolean enabled): 開(kāi)啟之后數(shù)據(jù)線將顯示成立體模式,對(duì)性能有影響 默認(rèn)關(guān)閉
  • setCubicIntensity(float intensity): 設(shè)置立體強(qiáng)度 最大值為1f, 最小0.05f,默認(rèn)0.2f
  • setCircleColor(int color): 設(shè)置圓形指示器的顏色
  • setCircleColors(List colors): 設(shè)置圓形指示器顏色
  • setCircleColorHole(int color): 設(shè)置圓形指示器內(nèi)部圓的顏色
  • setDrawCircleHole(boolean enabled): 設(shè)置是否繪制圓形指示器內(nèi)部圓
  • enableDashedLine(float lineLength, float spaceLength, float phase): 設(shè)置使用虛線數(shù)據(jù)線

BarDataSet

  • setBarSpacePercent(float percent): 設(shè)置條形圖間距百分比
  • setBarShadowColor(int color): 設(shè)置條形圖背景陰影顏色
  • setHighLightAlpha(int alpha): 設(shè)置條形圖背景高亮指示器的透明度,最小0(完全透明),最大255(完全顯示).
  • setStackLabels(String[] labels): 給層疊條形圖設(shè)置多個(gè)標(biāo)簽值

ScatterDataSet

  • setScatterShapeSize(float size): 設(shè)置形狀大小
  • setScatterShape(ScatterShape shape): 設(shè)置形狀樣式

CandleDataSet

  • setBodySpace(float space): 設(shè)置左右兩個(gè)蠟燭圖的間距,默認(rèn)0.1f(10%),最大0.45f,最小0f
  • setShadowWidth(float width): 設(shè)置蠟燭陰影線的寬度,默認(rèn)3f.
  • setShadowColor(int color): 設(shè)置陰影顏色.
  • setDecreasingColor(int color): 當(dāng)開(kāi)盤比收盤數(shù)據(jù)大時(shí),使用該顏色顯示.
  • setIncreasingColor(int color): 當(dāng)開(kāi)盤比收盤數(shù)據(jù)小時(shí),使用該顏色顯示.
  • setDecreasingPaintStyle(Paint.Style style): 當(dāng)開(kāi)盤比收盤數(shù)據(jù)大時(shí),使用該樣式繪制(填充或者描邊).
  • setIncreasingPaintStyle(Paint.Style style): 當(dāng)開(kāi)盤比收盤數(shù)據(jù)小時(shí),使用該樣式繪制(填充或者描邊).

BubbleDataSet

  • setHighlightCircleWidth(float width): 設(shè)置高亮圈的寬度

PieDataSet

  • setSliceSpace(float degrees): 設(shè)置分開(kāi)的餅圖兩片間的間距,默認(rèn):0沒(méi)有間距,最大20,最小0
  • setSelectionShift(float shift): 設(shè)置選中的餅圖片浮動(dòng)離開(kāi)中心點(diǎn)的距離,默認(rèn)12f




ViewPortHandler 視窗控制

初始化

通過(guò)以下方式來(lái)獲取視窗Handler實(shí)例

ViewPortHandler handler = chart.getViewPortHandler();

縮放和位移

  • getScaleX(): 獲取X軸縮放等級(jí).
  • getScaleY(): 獲取Y軸縮放等級(jí).
  • getTransX(): 獲取X軸上的位移量.
  • getTransY(): 獲取Y軸上的位移量.

圖表尺寸和內(nèi)容

  • getChartWidth(): 獲取圖表寬度
  • getChartHeight(): 獲取圖表高度
  • getContentRect(): 返回圖表內(nèi)容所在的矩形RectF對(duì)象.




FillFormatter接口 數(shù)據(jù)格式化

新建一個(gè)類實(shí)現(xiàn)FillFormatter接口

并重寫下面這個(gè)方法

public float getFillLinePosition(LineDataSet dataSet, LineDataProvider provider)

可以實(shí)現(xiàn)單個(gè)的DataSet的實(shí)現(xiàn)在哪個(gè)位置停止繪制

public class MyCustomFillFormatter implements FillFormatter {

    @Override
    public float getFillLinePosition(LineDataSet dataSet, LineDataProvider dataProvider) {

        float myDesiredFillPosition = ...;
        // put your logic here...

        return myDesiredFillPosition;
    }
}

把格式化添加到圖表中

lineDataSet.setFillFormatter(new MyCustomFillFormatter());

默認(rèn)的實(shí)現(xiàn)---->DefaultFillFormatter.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容