Charts

This chapter covers the basic setup for using this library.

  • 本章介紹使用此庫的基本設(shè)置。

1. Getting Started

Add dependency

  • 添加依賴

As a first step, add a dependency to this library to your project. How to do that is described in the usage section of this repository. Gradle is the recommended way of using this library as a dependency.

  • 首先矾削,將此庫的依賴項添加到項目中冈闭。 如何執(zhí)行此操作在此存儲庫的用法部分中進(jìn)行了描述火焰。 Gradle是使用此庫作為依賴項的推薦方法拆融。

Creating the View

For using a LineChart, BarChart, ScatterChart, CandleStickChart, PieChart, BubbleChart or RadarChart, define it in .xml:

  • 要使用LineChart染突,BarChart淘太,ScatterChart姻僧,CandleStickChart规丽,PieChart,BubbleChart或RadarChart撇贺,請在.xml中定義它:

And then retrieve it from your Activity, Fragment or whatever:

  • 然后從您的Activity赌莺,F(xiàn)ragment或其他內(nèi)容中檢索它:
  // in this example, a LineChart is initialized from xml
    LineChart chart = (LineChart) findViewById(R.id.chart);

or create it in code (and then add it to a layout):

  • 或者在代碼中創(chuàng)建它(然后將其添加到布局中):
    // programmatically create a LineChart
    LineChart chart = new LineChart(Context);

    // get a layout defined in xml
    RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
    rl.add(chart); // add the programmatically created chart

Adding data

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

After you have an instance of your chart, you can create data and add it to the chart. This example uses the LineChart, for which the Entry class represents a single entry in the chart with x- and y-coordinate. Other chart types, such as BarChart use other classes (e.g. BarEntry) for that purpose.

  • 擁有圖表實例后,您可以創(chuàng)建數(shù)據(jù)并將其添加到圖表中松嘶。 此示例使用LineChart艘狭,其中Entry類表示圖表中具有x和y坐標(biāo)的單個條目。 其他圖表類型(例如BarChart)為此目的使用其他類(例如BarEntry)翠订。

To add data to your chart, wrap each data object you have into an Entry object, like below:

  • 要向圖表添加數(shù)據(jù)巢音,請將您擁有的每個數(shù)據(jù)對象包裝到Entry對象中,如下所示:
YourData[] dataObjects = ...;

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

for (YourData data : dataObjects) {

    // turn your data into Entry objects
    entries.add(new Entry(data.getValueX(), data.getValueY())); 
}

As a next step, you need to add the List<Entry> you created to a LineDataSet object. DataSet objects hold data which belongs together, and allow individual styling of that data. The below used "Label" has only a descriptive purpose and shows up in the Legend, if enabled.

  • 下一步尽超,您需要將創(chuàng)建的List <Entry>添加到LineDataSet對象官撼。 DataSet對象保存屬于一起的數(shù)據(jù),并允許對該數(shù)據(jù)進(jìn)行單獨設(shè)計似谁。 以下使用的“標(biāo)簽”僅具有描述性目的歧寺,并在圖例中顯示(如果已啟用)。
LineDataSet dataSet = new LineDataSet(entries, "Label"); // add entries to dataset
dataSet.setColor(...);
dataSet.setValueTextColor(...); // styling, ...

As a last step, you need to add the LineDataSet object (or objects) you created to a LineData object. This object holds all data that is represented by a Chart instance and allows further styling. After creating the data object, you can set it to the chart and refresh it:

  • 最后一步棘脐,您需要將創(chuàng)建的LineDataSet對象(或多個對象)添加到LineData對象斜筐。 此對象包含由Chart實例表示的所有數(shù)據(jù),并允許進(jìn)一步樣式化蛀缝。 創(chuàng)建數(shù)據(jù)對象后顷链,您可以將其設(shè)置為圖表并刷新它:
LineData lineData = new LineData(dataSet);
chart.setData(lineData);
chart.invalidate(); // refresh

Please consider the scenario above a very basic setup. For a more detailed explanation please refer to the setting data section, which explains how to add data to various Chart types based on examples.

  • 請考慮上面的場景一個非常基本的設(shè)置屈梁。 有關(guān)更詳細(xì)的說明嗤练,請參閱設(shè)置數(shù)據(jù)部分,其中說明了如何根據(jù)示例將數(shù)據(jù)添加到各種圖表類型在讶。

Styling

For information about settings & styling of the chart surface and data, visit the general settings & styling section. Regarding more specific styling & settings for individual chart types, please have a look at the specific settings & styling wiki page.

  • 有關(guān)圖表表面和數(shù)據(jù)的設(shè)置和樣式的信息煞抬,請訪問常規(guī)設(shè)置和樣式部分。 有關(guān)各個圖表類型的更具體的樣式和設(shè)置构哺,請查看特定設(shè)置和樣式Wiki頁面革答。

2. Interaction with the Chart

This library allows you to fully customize the possible touch (and gesture) interaction with the chart-view and react to the interaction via callback-methods.

  • 該庫允許您完全自定義與圖表視圖的可能觸摸(和手勢)交互,并通過回調(diào)方法對交互作出反應(yīng)曙强。

Enabling / disabling interaction

  • setTouchEnabled(boolean enabled): Allows to enable/disable all possible touch-interactions with the chart.
    • setTouchEnabled(boolean enabled):允許啟用/禁用與圖表的所有可能的觸摸交互残拐。
  • setDragEnabled(boolean enabled): Enables/disables dragging (panning) for the chart.
    • setDragEnabled(boolean enabled):啟用/禁用圖表的拖動(平移)。
  • setScaleEnabled(boolean enabled): Enables/disables scaling for the chart on both axes.
    • setScaleEnabled(boolean enabled):啟用/禁用兩個軸上圖表的縮放碟嘴。
  • setScaleXEnabled(boolean enabled): Enables/disables scaling on the x-axis.
    • setScaleXEnabled(boolean enabled):啟用/禁用x軸縮放溪食。
  • setScaleYEnabled(boolean enabled): Enables/disables scaling on the y-axis.
    • setScaleYEnabled(boolean enabled):啟用/禁用y軸縮放。
  • setPinchZoom(boolean enabled): If set to true, pinch-zooming is enabled. If disabled, x- and y-axis can be zoomed separately.
    • setPinchZoom(boolean enabled):如果設(shè)置為true娜扇,則啟用縮放縮放错沃。 如果禁用栅组,則可以單獨縮放x軸和y軸。
  • setDoubleTapToZoomEnabled(boolean enabled): Set this to false to disallow zooming the chart via double-tap on it.
    • setDoubleTapToZoomEnabled(boolean enabled):將此值設(shè)置為false以禁止通過雙擊來縮放圖表枢析。

Chart fling / deceleration

  • 圖表fling /減速
  • setDragDecelerationEnabled(boolean enabled): If set to true, chart continues to scroll after touch up. Default: true.
    • setDragDecelerationEnabled(boolean enabled):如果設(shè)置為true玉掸,則圖表會在觸摸后繼續(xù)滾動。 默認(rèn)值:true登疗。
  • setDragDecelerationFrictionCoef(float coef): Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately. 1 is an invalid value, and will be converted to 0.9999 automatically.
    • setDragDecelerationFrictionCoef(float coef):減速摩擦系數(shù)[0; 1]間隔排截,較高的值表示速度將緩慢下降嫌蚤,例如辐益,如果設(shè)置為0,它將立即停止脱吱。 1是無效值智政,將自動轉(zhuǎn)換為0.9999。

Highlighting Values

  • 突出顯示值

How to allow highlighting entries via tap-gesture and programmatically is described int the highlightning section.

  • 如何允許通過點擊手勢和編程方式突出顯示條目在突出顯示部分中進(jìn)行了描述箱蝠。

Gesture callbacks

  • 手勢回調(diào)

The OnChartGestureListener will allow you to react to gestures made on the chart:

  • OnChartGestureListener將允許您對圖表上的手勢做出反應(yīng):
public interface OnChartGestureListener {

    /**
     * Callbacks when a touch-gesture has started on the chart (ACTION_DOWN) 
     * 在圖表上啟動觸摸手勢時回調(diào)(ACTION_DOWN)
     * @param me
     * @param lastPerformedGesture
     */
    void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture);

    /**
     * Callbacks when a touch-gesture has ended on the chart (ACTION_UP, ACTION_CANCEL)
     * 觸摸手勢在圖表上結(jié)束時的回調(diào)(ACTION_UP续捂,ACTION_CANCEL)
     * @param me
     * @param lastPerformedGesture
     */
    void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture);

    /**
     * Callbacks when the chart is longpressed.
     *  圖表被長按時回調(diào)。
     * @param me
     */
    public void onChartLongPressed(MotionEvent me);

    /**
     * Callbacks when the chart is double-tapped.
     *  雙擊圖表時的回調(diào)宦搬。
     * @param me
     */
    public void onChartDoubleTapped(MotionEvent me);
/**
     * Callbacks when the chart is single-tapped.
     *  單擊圖表時的回調(diào)牙瓢。
     * @param me
     */
    public void onChartSingleTapped(MotionEvent me);

    /**
     * Callbacks then a fling gesture is made on the chart.
     *  在圖表上做出一個驚人的手勢。
     * @param me1
     * @param me2
     * @param velocityX
     * @param velocityY
     */
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY);

   /**
     * Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
     *  當(dāng)圖表通過縮放縮放手勢縮放/縮放時间校。
     * @param me
     * @param scaleX scalefactor on the x-axis
     * @param scaleY scalefactor on the y-axis
     */
    public void onChartScale(MotionEvent me, float scaleX, float scaleY);

   /**
    * Callbacks when the chart is moved / translated via drag gesture.
    * 通過拖動手勢移動/翻譯圖表時的回調(diào)矾克。
    * @param me
    * @param dX translation distance on the x-axis  x軸上的平移距離
    * @param dY translation distance on the y-axis  y軸上的平移距離
    */
    public void onChartTranslate(MotionEvent me, float dX, float dY);
}

Simply let your class that should receive the callbacks implement this interface and set it as a listener to the chart:

  • 只需讓你的接收回調(diào)的類實現(xiàn)這個接口并將其設(shè)置為圖表的監(jiān)聽器:
chart.setOnChartGestureListener(this);

3. Highlighting Values

This section focuses on the topic of highlighting entries in the chart, both via tap-gesture and programmatically based on release v3.0.0.

  • 本節(jié)重點介紹通過tap-gesture和基于發(fā)行版v3.0.0以編程方式突出顯示圖表中條目的主題。

Enabling / Disabling highlighting

  • 啟用/禁用突出顯示
  • setHighlightPerDragEnabled(boolean enabled): Set this to true on your Chart to allow highlighting per dragging over the chart surface when it is fully zoomed out. Default: true
    • setHighlightPerDragEnabled(boolean enabled):在圖表上將此值設(shè)置為true憔足,以便在完全縮小時在圖表表面上進(jìn)行每次拖動時突出顯示胁附。 默認(rèn)值:true
  • setHighlightPerTapEnabled(boolean enabled): Set this to false on your Chart to prevent values from being highlighted by tap gesture. Values can still be highlighted via drag or programmatically. Default: true
    • setHighlightPerTapEnabled(boolean enabled):在圖表上將此設(shè)置為false,以防止通過點按手勢突出顯示值滓彰。 仍可通過拖動或以編程方式突出顯示值控妻。 默認(rèn)值:true
  • setMaxHighlightDistance(float distanceDp): Sets the maximum highlight distance in dp. Taps on the chart further away from an entry than that distance will not trigger a highlight. Default: 500dp
    • setMaxHighlightDistance(float distanceDp):設(shè)置dp中的最大高光距離。 在圖表上輕敲遠(yuǎn)離條目的距離不會觸發(fā)突出顯示揭绑。 默認(rèn)值:500dp

In addition to that, highlighting can be configured for individual DataSet objects:

  • 除此之外弓候,還可以為各個DataSet對象配置突出顯示:
 dataSet.setHighlightEnabled(true); // allow highlighting for DataSet

  // set this to false to disable the drawing of highlight indicator (lines)
  dataSet.setDrawHighlightIndicators(true); 
  dataSet.setHighlightColor(Color.BLACK); // color for highlight indicator
  // and more...

Highlighting programmatically

  • 以編程方式突出顯示

highlightValue(float x, int dataSetIndex, boolean callListener): Highlights the value at the given x-position in the given DataSet. Provide -1 as the dataSetIndex to undo all highlighting. The boolean flag determines wether the selection listener should be called or not.

  • highlightValue(float x,int dataSetIndex他匪,boolean callListener):突出顯示給定DataSet中給定x位置的值弓叛。 提供-1作為dataSetIndex以撤消所有突出顯示。 布爾標(biāo)志確定應(yīng)該調(diào)用選擇偵聽器還是不調(diào)用選擇偵聽器诚纸。

highlightValue(Highlight high, boolean callListener): Highlights the value represented by the provided Highlight object. Provide null to undo all highlighting. The boolean flag determines wether the selection listener should be called or not.

  • highlightValue(Highlight high撰筷,boolean callListener):突出顯示由提供的Highlight對象表示的值。 提供null以撤消所有突出顯示畦徘。 布爾標(biāo)志確定應(yīng)該調(diào)用選擇偵聽器還是不調(diào)用選擇偵聽器毕籽。

highlightValues(Highlight[] highs): Highlights the values represented by the given Highlight[] array. Provide null or an empty array to undo all highlighting.

  • highlightValues(Highlight[] highs):突出顯示給定Highlight []數(shù)組所表示的值抬闯。 提供null或空數(shù)組以撤消所有突出顯示。

getHighlighted(): Returns an Highlight[] array that contains information about all highlighted entries, their x-index and dataset-index.

  • getHighlighted():返回一個Highlight []數(shù)組关筒,其中包含有關(guān)所有突出顯示的條目溶握,x-index和dataset-index的信息。

Selection callbacks

  • 選擇回調(diào)

This library provides a number of listeners for callbacks upon interaction. One of them is the OnChartValueSelectedListener, for callbacks when highlighting values via touch:

  • 該庫在交互時為回調(diào)提供了許多偵聽器蒸播。 其中一個是OnChartValueSelectedListener睡榆,用于通過touch突出顯示值時的回調(diào):
public interface OnChartValueSelectedListener {
    /**
    * Called when a value has been selected inside the chart.
    * 在圖表中選擇值時調(diào)用。
    * @param e The selected Entry.
    * @param h The corresponding highlight object that contains information
    * about the highlighted position
    * 相應(yīng)的突出顯示對象袍榆,包含有關(guān)突出顯示位置的信息
    */
    public void onValueSelected(Entry e, Highlight h);
    /**
    * Called when nothing has been selected or an "un-select" has been made. 
    * 在未選擇任何內(nèi)容或已取消“取消選擇”時調(diào)用胀屿。
    */
    public void onNothingSelected();
}

Simply let your class that should receive the callbacks implement this interface and set it as a listener to the chart:

  • 只需讓你的接收回調(diào)的類實現(xiàn)這個接口并將其設(shè)置為圖表的監(jiān)聽器:
chart.setOnChartValueSelectedListener(this);

The Highlight class

  • 精彩集錦課程

The Highlight class represents all data associated with a highlighted Entry, such as the highlighted Entry object itself, the DataSet it belongs to, it's position on the drawing surface and more. It can be used to get information about an already highlighted Entry, or used to provide information to the Chart for an Entry to be highlighted. Regarding that purpose, the Highlight class provides two constructors:

  • Highlight類表示與突出顯示的Entry關(guān)聯(lián)的所有數(shù)據(jù),例如突出顯示的Entry對象本身包雀,它所屬的DataSet宿崭,它在繪圖表面上的位置等等。 它可用于獲取有關(guān)已突出顯示的條目的信息才写,或用于向圖表提供要突出顯示的條目的信息葡兑。 關(guān)于這個目的,Highlight類提供了兩個構(gòu)造函數(shù):
/** constructor for standard highlight */
// 標(biāo)準(zhǔn)高亮的構(gòu)造函數(shù)
 public Highlight(float x, int dataSetIndex) { ... }

 /** constructor for stacked BarEntry highlight */
// 堆疊BarEntry高亮顯示的構(gòu)造函數(shù)
 public Highlight(float x, int dataSetIndex, int stackIndex) { ... }

These constructors can be used to create a Highlight object which allows to perform highlighting programmatically:

  • 這些構(gòu)造函數(shù)可用于創(chuàng)建Highlight對象赞草,該對象允許以編程方式執(zhí)行突出顯示:
// highlight the entry and x-position 50 in the first (0) DataSet
// 突出顯示第一個(0)數(shù)據(jù)集中的條目和x位置50
Highlight highlight = new Highlight(50f, 0); 

chart.highlightValue(highlight, false); // highlight this value, don't call listener
// 突出顯示此值讹堤,不要調(diào)用偵聽器

Custom highlighter

All user input in the form of highlight gestures is internally processed by the default ChartHighlighter class. It is possible to replace the default highligher with a custom implementation using the below method:

  • 高亮手勢形式的所有用戶輸入都由默認(rèn)的ChartHighlighter類在內(nèi)部處理。 可以使用以下方法用自定義實現(xiàn)替換默認(rèn)的highligher:

setHighlighter(ChartHighlighter highlighter): Sets a custom highligher object for the chart that handles / processes all highlight touch events performed on the chart-view. Your custom highlighter object needs to extend the ChartHighlighter class.

  • setHighlighter(ChartHighlighter highlighter):為圖表設(shè)置自定義highligher對象厨疙,以處理/處理在圖表視圖上執(zhí)行的所有高光觸摸事件洲守。 您的自定義熒光筆對象需要擴(kuò)展ChartHighlighter類。

4. The Axis (AxisBase)

This wiki page focuses on the AxisBase class, the baseclass of both XAxis (XAxis) and YAxis(YAxis). Introduced in v2.0.0

  • 此Wiki頁面?zhèn)戎赜贏xisBase類轰异,XAxis(XAxis)和YAxis(YAxis)的基類岖沛。 在v2.0.0中引入

The following methods mentioned below can be applied to both axes.

  • 以下提到的方法可以應(yīng)用于兩個軸。

The axis classes allow specific styling and consist (can consist) of the following components/parts:
- 軸類允許特定樣式并包含(可以包含)以下組件/部件:

  • The labels (drawn in vertical (y-axis) or horizontal (x-axis) alignment), which contain the axis description values

    • 標(biāo)簽(以垂直(y軸)或水平(x軸)對齊繪制)搭独,包含軸描述值
  • A so called "axis-line" that is drawn directly next to and parallel to the labels

    • 所謂的“軸線”婴削,直接繪制在標(biāo)簽旁邊并與之平行
  • The "grid-lines", each originating from an axis-label in horizontal direction

    • “網(wǎng)格線”,每個都來自水平方向的軸標(biāo)簽
  • LimitLines, that allow to present special infomation, like borders or constraints

    • LimitLines牙肝,允許提供特殊信息唉俗,如邊框或約束

Control which parts (of the axis) should be drawn

  • 控制應(yīng)繪制哪些部分(軸)
  • setEnabled(boolean enabled): Sets the axis enabled or disabled. If disabled, no part of the axis will be drawn regardless of any other settings.
    • setEnabled(boolean enabled):設(shè)置啟用或禁用的軸。 如果禁用配椭,則無論其他任何設(shè)置如何虫溜,都不會繪制軸的任何部分。
  • setDrawLabels(boolean enabled): Set this to true to enable drawing the labels of the axis.
    • setDrawLabels(boolean enabled):將此屬性設(shè)置為true以啟用繪制軸標(biāo)簽股缸。
  • setDrawAxisLine(boolean enabled): Set this to true if the line alongside the axis (axis-line) should be drawn or not.
    • setDrawAxisLine(boolean enabled):如果應(yīng)該繪制沿軸(軸線)的線衡楞,則將其設(shè)置為true。
  • setDrawGridLines(boolean enabled): Set this to true to enable drawing the grid lines for the axis.
    • setDrawGridLines(boolean enabled):將此屬性設(shè)置為true以啟用繪制軸的網(wǎng)格線敦姻。

Customizing the axis range (min / max)

  • 自定義軸范圍(最小/最大)
  • setAxisMaximum(float max): Set a custom maximum value for this axis. If set, this value will not be calculated automatically depending on the provided data.

    • setAxisMaximum(float max):為此軸設(shè)置自定義最大值瘾境。如果設(shè)置歧杏,則不會根據(jù)提供的數(shù)據(jù)自動計算該值。
  • resetAxisMaximum(): Call this to undo a previously set maximum value. By doing this, you will again allow the axis to automatically calculate it's maximum.

    • resetAxisMaximum():調(diào)用此方法以撤消先前設(shè)置的最大值迷守。通過這樣做犬绒,您將再次允許軸自動計算它的最大值。
  • setAxisMinimum(float min): Set a custom minimum value for this axis. If set, this value will not be calculated automatically depending on the provided data.

    • setAxisMinimum(float min):為此軸設(shè)置自定義最小值兑凿。如果設(shè)置凯力,則不會根據(jù)提供的數(shù)據(jù)自動計算該值。
  • resetAxisMinimum(): Call this to undo a previously set minimum value. By doing this, you will again allow the axis to automatically calculate it's minimum.

    • resetAxisMinimum():調(diào)用此方法以撤消先前設(shè)置的最小值礼华。通過這樣做咐鹤,您將再次允許軸自動計算它的最小值。
  • setStartAtZero(boolean enabled): Deprecated - Use setAxisMinValue(...) or setAxisMaxValue(...) instead.

    • setStartAtZero(boolean enabled):不推薦使用 - 改為使用setAxisMinValue(...)或setAxisMaxValue(...)卓嫂。
  • setInverted(boolean enabled): If set to true, this axis will be inverted which means the highest value will be on the bottom, the lowest value on top.

    • setInverted(boolean enabled):如果設(shè)置為true慷暂,則此軸將被反轉(zhuǎn)聘殖,這意味著最高值將位于底部晨雳,最低值將位于頂部。
  • setSpaceTop(float percent): Sets the top spacing (in percent of the total axis-range) of the highest value in the chart in comparison to the highest value on the axis.

    • setSpaceTop(float percent):設(shè)置圖表中最高值的頂部間距(以總軸 - 范圍的百分比表示)與軸上的最高值進(jìn)行比較奸腺。
  • setSpaceBottom(float percent): Sets the bottom spacing (in percent of the total axis-range) of the lowest value in the chart in comparison to the lowest value on the axis.

    • setSpaceBottom(float percent):設(shè)置圖表中最低值的底部間距(以總軸 - 范圍的百分比表示)與軸上的最低值進(jìn)行比較餐禁。
  • setShowOnlyMinMax(boolean enabled): If enabled, this axis will only show it's minimum and maximum value. This will ignore/override the defined label-count (if not forced).

    • setShowOnlyMinMax(boolean enabled):如果啟用,此軸將僅顯示其最小值和最大值突照。這將忽略/覆蓋定義的標(biāo)簽計數(shù)(如果不強(qiáng)制)帮非。
  • setLabelCount(int count, boolean force): Sets the number of labels for the y-axis. Be aware that this number is not fixed (if force == false) and can only be approximated. If force is enabled (true), then the exact specified label-count is drawn - this can lead to uneven numbers on the axis.

    • setLabelCount(int count,boolean force):設(shè)置y軸的標(biāo)簽數(shù)讹蘑。請注意末盔,此數(shù)字不是固定的(如果force == false),并且只能近似座慰。如果強(qiáng)制啟用(true)陨舱,則繪制精確指定的標(biāo)簽計數(shù) - 這可能導(dǎo)致軸上的數(shù)字不均勻。
  • setPosition(YAxisLabelPosition pos): Sets the position where the axis-labels should be drawn. Either INSIDE_CHART or OUTSIDE_CHART.

    • setPosition(YAxisLabelPosition pos):設(shè)置應(yīng)繪制軸標(biāo)簽的位置版仔。 INSIDE_CHART或OUTSIDE_CHART游盲。
  • setGranularity(float gran): Sets the minimum interval between the y-axis values. This can be used to avoid value duplicating when zooming in to a point where the number of decimals set for the axis no longer allow to distinguish between two axis values.

    • setGranularity(float gran):設(shè)置y軸值之間的最小間隔。這可以用于避免在放大到為軸設(shè)置的小數(shù)位數(shù)不再允許區(qū)分兩個軸值的點時重復(fù)值蛮粮。
  • setGranularityEnabled(boolean enabled): Enables the granularity feature that limits the interval of the y-axis when zooming in. Default: false

    • setGranularityEnabled(boolean enabled):啟用粒度特征益缎,在放大時限制y軸的間隔。默認(rèn)值:false

Styling / modifying the axis

  • 造型/修改軸
  • setTextColor(int color): Sets the color of the axis labels.
    • setTextColor(int color):設(shè)置軸標(biāo)簽的顏色然想。
  • setTextSize(float size): Sets the text-size of the axis labels in dp.
    • setTextSize(float size):以dp為單位設(shè)置軸標(biāo)簽的文本大小莺奔。
  • setTypeface(Typeface tf): Sets a custom Typeface for the axis labels.
    • setTypeface(Typeface tf):為軸標(biāo)簽設(shè)置自定義字體。
  • setGridColor(int color): Sets the color of the grid-lines of this axis.
    • setGridColor(int color):設(shè)置此軸的網(wǎng)格線的顏色变泄。
  • setGridLineWidth(float width): Sets the width of the grid-lines of this axis.
    • setGridLineWidth(float width):設(shè)置此軸的網(wǎng)格線的寬度令哟。
  • setAxisLineColor(int color): Sets the color of the axis-line of this axis.
    • setAxisLineColor(int color):設(shè)置此軸的軸線顏色熙卡。
  • setAxisLineWidth(float width): Sets the width of the axis-line of this axis.
    • setAxisLineWidth(float width):設(shè)置此軸的軸線寬度。
  • enableGridDashedLine(float lineLength, float spaceLength, float phase): Enables the grid line to be drawn in dashed mode, e.g. like this "- - - - - -". "lineLength" controls the length of the line pieces, "spaceLength" controls the space between the lines, "phase" controls the starting point.
    • enableGridDashedLine(float lineLength励饵,float spaceLength驳癌,float phase):使網(wǎng)格線以虛線模式繪制,例如: 像這樣 ”- - - - - -”役听。 “l(fā)ineLength”控制線條的長度颓鲜,“spaceLength”控制線條之間的空間,“phase”控制起始點典予。

Formatting axis values

  • 格式化軸值

For formatting axis values, you can use the IAxisValueFormatter interface, which is explained here. You can use the axis.setValueFormatter(IAxisValueFormatter formatter) method to set your custom formatter to the axis.

  • 要格式化軸值甜滨,可以使用IAxisValueFormatter接口,此處將對此進(jìn)行說明瘤袖。 您可以使用axis.setValueFormatter(IAxisValueFormatter formatter)方法將自定義格式化程序設(shè)置為軸衣摩。

Limit Lines

  • 限制線

Both axes support so called LimitLines that allow to present special information, like borders or constraints. LimitLines added to the YAxis are drawn in horizontal direction, and in vertical direction when added to the XAxis. This is how you add and remove LimitLines from the axis:

  • 兩個軸都支持所謂的LimitLines,它允許提供特殊信息捂敌,如邊界或約束艾扮。 添加到Y(jié)Axis的LimitLines在水平方向上繪制,在添加到XAxis時在垂直方向上繪制占婉。 這是您從軸添加和刪除LimitLines的方法:
  • addLimitLine(LimitLine l): Adds a new LimitLine to this axis.
    • addLimitLine(LimitLine l):向此軸添加新的LimitLine泡嘴。
  • removeLimitLine(LimitLine l): Removes the
    specified LimitLine from this axis.
    • removeLimitLine(LimitLine l):從此軸移除指定的LimitLine。
  • More methods for adding / removing available as well.
    • 更多添加/刪除方法也可用逆济。
  • setDrawLimitLinesBehindData(boolean enabled): Allows to control the z-order between the LimitLines and the actual data. If this is set to true, the LimitLines are drawn behind the actual data, otherwise on top. Default: false
    • setDrawLimitLinesBehindData(boolean enabled):允許控制LimitLines和實際數(shù)據(jù)之間的z順序酌予。 如果將此值設(shè)置為true,則會在實際數(shù)據(jù)后面繪制LimitLines奖慌,否則將在頂部繪制抛虫。 默認(rèn)值:false

Limit lines (class LimitLine) are (as the name might indicate) plain and simple lines can be used to provide additional information for the user.
- 限制行(類LimitLine)是(如名稱所示)簡單行和簡單行可用于為用戶提供附加信息。

As an example, your chart might display various blood pressure measurement results the user logged with an application. In order to inform the user that a systolic blood pressure of over 140 mmHg is considered to be a health risk, you could add a LimitLine at 140 to provide that information.
- 例如简僧,您的圖表可能會顯示用戶使用應(yīng)用程序記錄的各種血壓測量結(jié)果建椰。 為了告知用戶收縮壓超過140 mmHg被認(rèn)為是健康風(fēng)險,您可以在140處添加LimitLine以提供該信息涎劈。

Example Code

YAxis leftAxis = chart.getAxisLeft();

LimitLine ll = new LimitLine(140f, "Critical Blood Pressure");
ll.setLineColor(Color.RED);
ll.setLineWidth(4f);
ll.setTextColor(Color.BLACK);
ll.setTextSize(12f);
// .. and more styling options

leftAxis.addLimitLine(ll);

5. XAxis

The XAxis is a subclass of AxisBase from which it inherits a number of styling and convenience methods.

  • XAxis是AxisBase的子類广凸,它繼承了許多樣式和方便方法。

The XAxis class (in versions prior to 2.0.0 XLabels called), is the data and information container for everything related to the the horizontal axis. Each Line-, Bar-, Scatter-, CandleStick- and RadarChart has an XAxis object.

  • XAxis類(在2.0.0 XLabels之前的版本中稱為)蛛枚,是與水平軸相關(guān)的所有內(nèi)容的數(shù)據(jù)和信息容器谅海。 每個Line-,Bar-蹦浦,Scatter-扭吁,CandleStick-和RadarChart都有一個XAxis對象。

The XAxis class allows specific styling and consists (can consist) of the following components/parts:

  • XAxis類允許特定樣式,并包含(可以包含)以下組件/部件:
  • A so called "axis-line" that is drawn directly next to and parallel to the labels
    • 所謂的“軸線”侥袜,直接繪制在標(biāo)簽旁邊并與之平行
  • The "grid-lines", each originating from an axis-label in vertical direction
    • “網(wǎng)格線”蝌诡,每個都來自垂直方向的軸標(biāo)簽

In order to acquire an instance of the XAxis class, do the following:
- 要獲取XAxis類的實例,請執(zhí)行以下操作:

XAxis xAxis = chart.getXAxis();

Customizing the axis values

  • 自定義軸值
  • setLabelRotationAngle(float angle): Sets the angle for drawing the x-axis labels (in degrees).
    • setLabelRotationAngle(float angle):設(shè)置繪制x軸標(biāo)簽的角度(以度為單位)枫吧。
  • setPosition(XAxisPosition pos): Sets the position where the XAxis should appear. Choose between TOP, BOTTOM, BOTH_SIDED, TOP_INSIDE or BOTTOM_INSIDE.
    • setPosition(XAxisPosition pos):設(shè)置XAxis應(yīng)出現(xiàn)的位置浦旱。 選擇TOP,BOTTOM九杂,BOTH_SIDED颁湖,TOP_INSIDE或BOTTOM_INSIDE。

Example Code

  • 示例代碼
XAxis xAxis = chart.getXAxis();
xAxis.setPosition(XAxisPosition.BOTTOM);
xAxis.setTextSize(10f);
xAxis.setTextColor(Color.RED);
xAxis.setDrawAxisLine(true);
xAxis.setDrawGridLines(false);
// set a custom value formatter
xAxis.setValueFormatter(new MyCustomFormatter()); 
// and more...

6. YAxis

The YAxis is a subclass of AxisBase. This wiki entry only describes the YAxis, not it's superclass.

  • YAxis是AxisBase的子類例隆。 這個wiki條目只描述了YAxis甥捺,而不是它的超類。

The YAxis class (in versions older than 2.0.0 YLabels called), is the data and information container for everything related with the vertical-axis. Each Line-, Bar-, Scatter or CandleStickChart has a left and a right YAxis object, responsible for either the left, or the right axis respectively. The RadarChart has only one YAxis. By default, both axes of the chart are enabled and will be drawn.

  • YAxis類(在早于2.0.0 YLabels的版本中稱為)是與垂直軸相關(guān)的所有內(nèi)容的數(shù)據(jù)和信息容器镀层。 每個Line-镰禾,Bar-,Scatter或CandleStickChart都有一個左右YAxis對象唱逢,分別負(fù)責(zé)左軸或右軸吴侦。 RadarChart只有一個YAxis。 默認(rèn)情況下惶我,圖表的兩個軸都已啟用并將被繪制妈倔。

In order to acquire an instance of the YAxis class, call one of the following methods:

  • 要獲取YAxis類的實例博投,請調(diào)用以下方法之一:
YAxis leftAxis = chart.getAxisLeft();
YAxis rightAxis = chart.getAxisRight();

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

YAxis yAxis = radarChart.getYAxis(); // this method radarchart only

At runtime, use public AxisDependency getAxisDependency() to determine the side of the chart this axis represents.

  • 在運行時绸贡,使用public AxisDependency getAxisDependency()來確定此軸表示的圖表的一側(cè)。

Customizations that affect the value range of the axis need to be applied before setting data for the chart.

  • 在為圖表設(shè)置數(shù)據(jù)之前毅哗,需要應(yīng)用影響軸值范圍的自定義听怕。

Axis Dependency

  • 軸依賴性

Per default, all data that is added to the chart plots against the left YAxis of the chart. If not further specified and enabled, the right YAxis is adjusted to represent the same scale as the left axis.

  • 默認(rèn)情況下,添加到圖表的所有數(shù)據(jù)都會繪制在圖表的左側(cè)YAxis上虑绵。 如果未進(jìn)一步指定和啟用尿瞭,則調(diào)整右YAxis以表示與左軸相同的比例。

If your chart needs to support different axis scales, you can achieve that by setting the axis your data should plot against. This can be done by changing the AxisDependency of your DataSet object:

  • 如果您的圖表需要支持不同的軸刻度翅睛,您可以通過設(shè)置數(shù)據(jù)應(yīng)繪制的軸來實現(xiàn)声搁。 這可以通過更改DataSet對象的AxisDependency來完成:
LineDataSet dataSet = ...; // get a dataset
dataSet.setAxisDependency(AxisDependency.RIGHT);

Setting this will change the axis your data is plotted against.

The zero line

  • 零線

Besides the grid-lines, that originate horizontally alongside each value on the YAxis, there is the so called zeroline, which is drawn at the zero (0) value on the axis, and is similar to the grid-lines but can be configured separately.

  • 除了在YAxis上沿著每個值水平起源的網(wǎng)格線之外,還有所謂的零點捕发,它在軸上的零(0)值處繪制疏旨,并且類似于網(wǎng)格線但可以單獨配置。
  • setDrawZeroLine(boolean enabled): Enables / disables drawing the zero-line.
    • setDrawZeroLine(boolean enabled):啟用/禁用繪制零線扎酷。
  • setZeroLineWidth(float width): Sets the line-width of the zero line.
    • setZeroLineWidth(float width):設(shè)置零線的行寬檐涝。
  • setZeroLineColor(int color): Sets the color the zero-line should have.
    • setZeroLineColor(int color):設(shè)置零線應(yīng)具有的顏色咽块。

Zero-line example code:

// data has AxisDependency.LEFT
YAxis left = mChart.getAxisLeft();
left.setDrawLabels(false); // no axis labels
left.setDrawAxisLine(false); // no axis line
left.setDrawGridLines(false); // no grid lines
left.setDrawZeroLine(true); // draw a zero line
mChart.getAxisRight().setEnabled(false); // no right axis

The above code will result in a zero-line like shown in the image below. No axis values are drawn, no grid lines or axis lines are drawn, just a zero line.

  • 上面的代碼將產(chǎn)生如下圖所示的零線枷畏。 不繪制軸值,不繪制網(wǎng)格線或軸線,只繪制零線情组。
image.png

More example code

YAxis yAxis = mChart.getAxisLeft();
yAxis.setTypeface(...); // set a different font
yAxis.setTextSize(12f); // set the text size
yAxis.setAxisMinimum(0f); // start at zero
yAxis.setAxisMaximum(100f); // the axis maximum is 100
yAxis.setTextColor(Color.BLACK);
yAxis.setValueFormatter(new MyValueFormatter());
yAxis.setGranularity(1f); // interval 1
yAxis.setLabelCount(6, true); // force 6 labels
//... and more

7. Setting Data

This chapter covers the topic of setting data to various kinds of Charts.

  • 本章介紹了為各種圖表設(shè)置數(shù)據(jù)的主題。

LineChart

If you want to add values (data) to the chart, it has to be done via the

  • 如果要將值(數(shù)據(jù))添加到圖表中永罚,則必須通過
public void setData(ChartData data) { ... }

method. The baseclass ChartData (ChartData) class encapsulates all data and information that is needed for the chart during rendering. For each type of chart, a different subclass of ChartData (e.g. LineData) exists that should be used for setting data for the chart. In the constructor, you can hand over an List<? extends IDataSet> as the values to display. Below is an example with the class LineData (extends ChartData), which is used for adding data to a LineChart:

  • 方法悯森。 基類ChartData(ChartData)類封裝了呈現(xiàn)期間圖表所需的所有數(shù)據(jù)和信息。 對于每種類型的圖表巷怜,都存在ChartData的不同子類(例如LineData)陵叽,應(yīng)該用于設(shè)置圖表的數(shù)據(jù)。 在構(gòu)造函數(shù)中丛版,您可以移交List <巩掺? 將IDataSet>擴(kuò)展為要顯示的值。 下面是LineData類(擴(kuò)展ChartData)的示例页畦,它用于向LineChart添加數(shù)據(jù):
  /** List constructor */
    public LineData(List<ILineDataSet> sets) { ... }

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

So, what is a DataSet and why do you need it? That is actually pretty simple. One DataSet object represents a group of entries (e.g. class Entry) inside the chart that belong together. It is designed to logically separate different groups of values in the chart. For each type of chart, a differnt object that extends DataSet (e.g. LineDataSet) exists that allows specific styling.

  • 那么胖替,什么是DataSet以及為什么需要它? 這實際上非常簡單豫缨。 一個DataSet對象表示圖表內(nèi)屬于一起的一組條目(例如独令,類條目)。 它旨在邏輯上分離圖表中的不同值組好芭。 對于每種類型的圖表燃箭,存在擴(kuò)展DataSet(例如LineDataSet)的不同對象,其允許特定樣式舍败。

As an example, you might want to display the quarterly revenue of two different companies over one year in a LineChart. In that case, it would be recommended to create two different LineDataSet objects, each containing four values (one for each quarter).

  • 例如招狸,您可能希望在LineChart中顯示一年內(nèi)兩家不同公司的季度收入。 在這種情況下邻薯,建議創(chuàng)建兩個不同的LineDataSet對象裙戏,每個對象包含四個值(每個季度一個)。

Of course, it is also possible to provide just one LineDataSet object containing all 8 values for the two companys.

  • 當(dāng)然厕诡,也可以只提供一個包含兩個公司的所有8個值的LineDataSet對象累榜。

So how to setup a LineDataSet object?

  • 那么如何設(shè)置LineDataSet對象呢?
public LineDataSet(List<Entry> entries, String label) { ... }

When looking at the constructor (different constructors are available), it is visible that the LineDataSet needs an List of type Entry and a String used to describe the LineDataSet and as a label used for the Legend. Furthermore this label can be used to find the LineDataSet amongst other LineDataSet objects in the LineData object.

  • 在查看構(gòu)造函數(shù)(不同的構(gòu)造函數(shù)可用)時灵嫌,可以看到LineDataSet需要一個類型為Entry的List和一個用于描述LineDataSet的String以及一個用于Legend的標(biāo)簽壹罚。 此外,此標(biāo)簽可用于在LineData對象中的其他LineDataSet對象中查找LineDataSet寿羞。

The List of type Entry encapsulates all values of the chart. A Entry object is an additional wrapper around an entry in the chart with a x- and y-value:

  • Entry類型列表封裝了圖表的所有值猖凛。 Entry對象是圖表中具有x值和y值的條目的附加包裝器:
public Entry(float x, float y) { ... }

Putting it all together (example of two companies with quarterly revenue over one year):

  • 總而言之(兩家公司的季度收入超過一年的例子):

At first, create the lists of type Entry that will hold your values:

  • 首先,創(chuàng)建將保存您的值的Entry類型列表:
List<Entry> valsComp1 = new ArrayList<Entry>();
    List<Entry> valsComp2 = new ArrayList<Entry>();

Then, fill the lists with Entry objects. Make sure the entry objects contain the correct indices to the x-axis. (of course, a loop can be used here, in that case, the counter variable of the loop could be the index on the x-axis).

  • 然后稠曼,使用Entry對象填充列表形病。 確保條目對象包含x軸的正確索引客年。 (當(dāng)然,這里可以使用循環(huán)漠吻,在這種情況下量瓜,循環(huán)的計數(shù)器變量可以是x軸上的索引)。
Entry c1e1 = new Entry(0f, 100000f); // 0 == quarter 1
    valsComp1.add(c1e1);
    Entry c1e2 = new Entry(1f, 140000f); // 1 == quarter 2 ...
    valsComp1.add(c1e2);
    // and so on ...
    
    Entry c2e1 = new Entry(0f, 130000f); // 0 == quarter 1
    valsComp2.add(c2e1);
    Entry c2e2 = new Entry(1f, 115000f); // 1 == quarter 2 ...
    valsComp2.add(c2e2);
    //...

Now that we have our lists of Entry objects, the LineDataSet objects can be created:

  • 現(xiàn)在我們有了Entry對象列表途乃,可以創(chuàng)建LineDataSet對象:
LineDataSet setComp1 = new LineDataSet(valsComp1, "Company 1");
    setComp1.setAxisDependency(AxisDependency.LEFT);
    LineDataSet setComp2 = new LineDataSet(valsComp2, "Company 2");
    setComp2.setAxisDependency(AxisDependency.LEFT);

By calling setAxisDependency(...), the axis the DataSet should be plotted against is specified. Last but not least, we create a list of IDataSets and build our ChartData object:

  • 通過調(diào)用setAxisDependency(...)绍傲,可以指定DataSet應(yīng)繪制的軸。 最后但并非最不重要的是耍共,我們創(chuàng)建了一個IDataSets列表并構(gòu)建了我們的ChartData對象:
// use the interface ILineDataSet
    List<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
    dataSets.add(setComp1);
    dataSets.add(setComp2);
    
    LineData data = new LineData(dataSets);
    mLineChart.setData(data);
    mLineChart.invalidate(); // refresh

After calling invalidate() the chart is refreshed and the provided data is drawn.

  • 調(diào)用invalidate()后烫饼,將刷新圖表并繪制提供的數(shù)據(jù)。

If we want to add more descriptive values to the x-axis (instead of numbers ranging from 0 to 3 for the different quarters), we can do so by using the IAxisValueFormatter interface. This interface allows custom styling of values drawn on the XAxis. In this example, the formatter could look like this:

  • 如果我們想要為x軸添加更多描述性值(而不是不同季度的0到3之間的數(shù)字)试读,我們可以通過使用IAxisValueFormatter接口來實現(xiàn)杠纵。 此界面允許自定義XAxis上繪制的值的樣式。 在此示例中钩骇,formatter可能如下所示:
// the labels that should be drawn on the XAxis 
// 應(yīng)該在XAxis上繪制的標(biāo)簽
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];
    }

    // we don't draw numbers, so no decimal digits needed
// 我們不繪制數(shù)字比藻,因此不需要十進(jìn)制數(shù)字
    @Override
    public int getDecimalDigits() {  return 0; }
};

XAxis xAxis = mLineChart.getXAxis();
xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
xAxis.setValueFormatter(formatter);

Detailed information concerning the IAxisValueFormatter interface can be found here.

  • 有關(guān)IAxisValueFormatter接口的詳細(xì)信息,請參見此處倘屹。

If additional styling is applied, the LineChart resulting from this example should look similar to the one below:

  • 如果應(yīng)用了其他樣式银亲,則此示例生成的LineChart應(yīng)類似于下面的樣式:
image.png

Setting data for normal BarChart, ScatterChart, BubbleChart and CandleStickChartworks similar to the LineChart. A special case is the BarChart with multiple (grouped) bars, which will be explained below.

  • 設(shè)置正常BarChart,ScatterChart纽匙,BubbleChart和CandleStickChartworks的數(shù)據(jù)類似于LineChart务蝠。 一個特例是帶有多個(分組)條形的BarChart,下面將對此進(jìn)行說明烛缔。

The order of entries

  • 條目的順序

Please be aware that this library does not officially support drawing LineChart data from an Entry list not sorted by the x-position of the entries in ascending manner. Adding entries in an unsorted way may result in correct drawing, but may also lead to unexpected behaviour. A Listof Entry objects can be sorted manually or using the EntryXComparator:

  • 請注意馏段,此庫不正式支持從條目列表中繪制LineChart數(shù)據(jù),而不是按條目的x位置按升序排序力穗。 以未分類的方式添加條目可能會導(dǎo)致正確繪制毅弧,但也可能導(dǎo)致意外行為。 可以手動或使用EntryXComparator對Listof Entry對象進(jìn)行排序:
List<Entry> entries = ...;
Collections.sort(entries, new EntryXComparator());

The reason why this is required is because the library uses binary search algorithms for better performance only working on sorted lists.

  • 之所以需要這樣做是因為該庫使用二進(jìn)制搜索算法以獲得更好的性能当窗,僅用于排序列表。

BarChart

The way data can be set for a BarChart is very similar to the LineChart. The major difference are the data objects that need to be used for setting the data (e.g. BarEntry instead of Entry). In addition to that, the BarChart has different styling options.

  • 為BarChart設(shè)置數(shù)據(jù)的方式與LineChart非常相似寸宵。 主要區(qū)別是需要用于設(shè)置數(shù)據(jù)的數(shù)據(jù)對象(例如BarEntry而不是Entry)崖面。 除此之外,BarChart還有不同的造型選擇梯影。

Consider the following example of filling a BarChart with data:

  • 請考慮以下使用數(shù)據(jù)填充BarChart的示例:
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)); 
                                    // gap of 2f
entries.add(new BarEntry(5f, 70f));
entries.add(new BarEntry(6f, 60f));

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

In the above example, five BarEntry objects were created and added to a BarDataSet. Notice that there is a gap of "2" on the x-position between the fourth and fifth entry. In this example, this gap is used to explain how the positioning of bars in the BarChart works. The screenshot in the end of this tutorial will show the resulting BarChart for the given data. As a next step, a BarData object needs to be created:

  • 在上面的示例中巫员,創(chuàng)建了五個BarEntry對象并將其添加到BarDataSet。 請注意甲棍,第四個和第五個條目之間的x位置存在“2”的間隙简识。 在此示例中,此間隙用于解釋BarChart中柱的定位如何工作。 本教程末尾的屏幕截圖將顯示給定數(shù)據(jù)的結(jié)果BarChart七扰。 下一步奢赂,需要創(chuàng)建一個BarData對象:
BarData data = new BarData(set);
data.setBarWidth(0.9f); // set custom bar width
chart.setData(data);
chart.setFitBars(true); // make the x-axis fit exactly all bars
chart.invalidate(); // refresh

In the above snippet, a BarData object was created. When the BarEntry objects for the chart were created, we left a space of "1f" on the x-axis between (the centres) of each bar. By setting the bar-width to 0.9f, we effectively create a space of 0.1f between each bar. The setFitBars(true) call will tell the chart to adjust it's range of x-axis values to exactly fit all bars, and no bars are cut off on the sides.

  • 在上面的代碼片段中,創(chuàng)建了一個BarData對象颈走。 當(dāng)創(chuàng)建圖表的BarEntry對象時膳灶,我們在每個條形(中心)之間的x軸上留下了“1f”的空間。 通過將條寬設(shè)置為0.9f立由,我們有效地在每個條之間創(chuàng)建0.1f的空間轧钓。 setFitBars(true)調(diào)用將告訴圖表調(diào)整它的x軸值范圍以完全適合所有條形,并且兩側(cè)不會切斷條形锐膜。

After creating the BarData object, we set it to the chart and refresh. The result should look close to the one shown below:

  • 創(chuàng)建BarData對象后毕箍,我們將其設(shè)置為圖表并刷新。 結(jié)果應(yīng)該看起來接近下面顯示的結(jié)果:
image.png

Grouped BarChart

Since release v3.0.0, MPAndroidChart supports drawing bars explicitly grouped (in this case the library will handle the x-position), or user defined, which means that the user can place the bars anywhere he wants by altering the x-position of the bar.

  • 從版本v3.0.0開始道盏,MPAndroidChart支持明確分組的繪圖條(在這種情況下霉晕,庫將處理x位置)或用戶定義,這意味著用戶可以通過更改x位置將條放置在他想要的任何位置捞奕。 酒吧牺堰。

This section will focus on explicit grouped BarChart, which means that the library will handle the x-positions of the bars. Consider the following example setup:

  • 本節(jié)將重點介紹顯式分組BarChart,這意味著庫將處理條形的x位置颅围。 請考慮以下示例設(shè)置:
YourData[] group1 = ...;
YourData[] group2 = ...;

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

// fill the lists
for(int i = 0; i < group1.length; i++) {
    entriesGroup1.add(new BarEntry(i, group1.getValue()));
    entriesGroup2.add(new BarEntry(i, group2.getValue()));
}

BarDataSet set1 = new BarDataSet(entriesGroup1, "Group 1");
BarDataSet set2 = new BarDataSet(entriesGroup2, "Group 2");

In this example case, we will have two groups of bars, each represented by an individual BarDataSet. In case of explicit (library handled) groups, the actual x-position of the entries does not matter. Grouping is performed based on the position of the BarEntry in the entries List.

  • 在這個示例中伟葫,我們將有兩組條形圖,每條條形圖由一個單獨的BarDataSet表示院促。 在顯式(庫處理)組的情況下筏养,條目的實際x位置無關(guān)緊要。 基于條目列表中BarEntry的位置執(zhí)行分組常拓。
float groupSpace = 0.06f;
float barSpace = 0.02f; // x2 dataset
float barWidth = 0.45f; // x2 dataset
// (0.02 + 0.45) * 2 + 0.06 = 1.00 -> interval per "group"

BarData data = new BarData(set1, set2);
data.setBarWidth(barWidth); // set the width of each bar
barChart.setData(data);
barChart.groupBars(1980f, groupSpace, barSpace); // perform the "explicit" grouping
barChart.invalidate(); // refresh

In the code snippet above, the BarDataSet objects are added to a BarChart. The groupBars(...) method performs the grouping of the two BarDataSet objects. The method takes the following parameters:

  • 在上面的代碼片段中渐溶,BarDataSet對象被添加到BarChart中。 groupBars(...)方法執(zhí)行兩個BarDataSet對象的分組弄抬。 該方法采用以下參數(shù):
public void groupBars(float fromX, float groupSpace, float barSpace) { ... }

The fromX parameter determines where on the XAxis the grouped bars should start (in this case "1980"), the groupSpace determines the space left in between each group of bars, and the barSpace determines the space between individual bars of a group. Based on these parameters, the groupBars(...) method alters the position of each bar on the XAxis towards a grouped appearance, preserving the order of the individual BarEntry objects.

  • fromX參數(shù)確定分組條應(yīng)該從XAxis開始的位置(在本例中為“1980”)茎辐,groupSpace確定每組條之間留下的空間,barSpace確定組中各個條之間的間距掂恕。 基于這些參數(shù)拖陆,groupBars(...)方法將XAxis上每個條形的位置改變?yōu)榉纸M外觀,從而保留各個BarEntry對象的順序懊亡。

The "interval" (occupied space) each group has on the XAxis is also defined by the groupSpace and barSpace parameters, and the barWidth.

  • 每個組在XAxis上具有的“間隔”(占用空間)也由groupSpace和barSpace參數(shù)以及barWidth定義依啰。

The result should look somewhat like this:

  • 結(jié)果應(yīng)該看起來像這樣:
image.png

Of course a grouped BarChart can also be achieved without the use of the groupBars(...) method, by simply positioning the individual bars correctly on the XAxis manually.

  • 當(dāng)然,通過簡單地手動將各個條正確地放置在XAxis上店枣,也可以在不使用groupBars(...)方法的情況下實現(xiàn)分組的BarChart速警。

In order to make sure the labels of the XAxis are centered above the groups like in the screenshot above, you can use the setCenterAxisLabels(...) method:

  • 為了確保XAxis的標(biāo)簽位于組上方叹誉,如上面的屏幕截圖所示,您可以使用setCenterAxisLabels(...)方法:
XAxis xAxis = chart.getXAxis();
xAxis.setCenterAxisLabels(true);

Stacked BarChart

The stacked BarChart setup is completely similar to normal BarChart, with the exception being the way the individual BarEntry objects are created. In case of stacked bars, a different constructor for the BarEntry has to be used:

  • 堆疊的BarChart設(shè)置與普通的BarChart完全相似闷旧,但創(chuàng)建單個BarEntry對象的方式除外长豁。 如果是堆疊條形,則必須使用BarEntry的不同構(gòu)造函數(shù):
public BarEntry(float x, float [] yValues) { ... }

This constructor allows to provide multiple yValues, which represent the values of the "stack" of each bar. Consider the following example object:

  • 此構(gòu)造函數(shù)允許提供多個y值鸠匀,表示每個條的“堆椊缎保”的值。 請考慮以下示例對象:
BarEntry stackedEntry = new BarEntry(0f, new float[] { 10, 20, 30 });

This BarEntry has consists of a stack of three values, having a "height" of "10", "20" and "30".

  • 該BarEntry由三個值組成缀棍,其“高度”為“10”宅此,“20”和“30”。

PieChart

Unlike other chart types, the PieChart takes data in form of PieEntry objects. The constructor for these objects looks as follows:

  • 與其他圖表類型不同爬范,PieChart以PieEntry對象的形式獲取數(shù)據(jù)父腕。 這些對象的構(gòu)造函數(shù)如下所示:
public PieEntry(float value, String label) { ... }

The first parameter of the constructor is used for the actual "value" that should be drawn as a pie-slice in the PieChart. The second String parameter called "label" is used to provide additional description of the slice. Consider the following example PieChart setup:

  • 構(gòu)造函數(shù)的第一個參數(shù)用于實際的“值”,應(yīng)該在PieChart中將其繪制為餅圖青瀑。 名為“l(fā)abel”的第二個String參數(shù)用于提供切片的其他描述璧亮。 請考慮以下示例PieChart設(shè)置:
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(); // refresh

The PieEntry objects to not hold a value for the x-position because the order of the PieEntry objects displayed in the chart is determined by their order in the entries list.

  • PieEntry對象不保存x位置的值,因為圖表中顯示的PieEntry對象的順序由它們在條目列表中的順序確定斥难。

When adding some additional styling, the resulting PieChart with the data used above could look similar to this:

  • 添加一些額外的樣式時枝嘶,生成的PieChart與上面使用的數(shù)據(jù)可能類似于:
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市哑诊,隨后出現(xiàn)的幾起案子群扶,更是在濱河造成了極大的恐慌,老刑警劉巖镀裤,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件竞阐,死亡現(xiàn)場離奇詭異,居然都是意外死亡暑劝,警方通過查閱死者的電腦和手機(jī)骆莹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來担猛,“玉大人幕垦,你說我怎么就攤上這事』傧埃” “怎么了智嚷?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長纺且。 經(jīng)常有香客問我,道長稍浆,這世上最難降的妖魔是什么载碌? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任猜嘱,我火速辦了婚禮,結(jié)果婚禮上嫁艇,老公的妹妹穿的比我還像新娘朗伶。我一直安慰自己,他們只是感情好步咪,可當(dāng)我...
    茶點故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布论皆。 她就那樣靜靜地躺著,像睡著了一般猾漫。 火紅的嫁衣襯著肌膚如雪点晴。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天悯周,我揣著相機(jī)與錄音粒督,去河邊找鬼。 笑死禽翼,一個胖子當(dāng)著我的面吹牛屠橄,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播闰挡,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼锐墙,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了长酗?” 一聲冷哼從身側(cè)響起溪北,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎花枫,沒想到半個月后刻盐,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡劳翰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年敦锌,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片佳簸。...
    茶點故事閱讀 39,779評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡乙墙,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出生均,到底是詐尸還是另有隱情听想,我是刑警寧澤,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布马胧,位于F島的核電站汉买,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏佩脊。R本人自食惡果不足惜蛙粘,卻給世界環(huán)境...
    茶點故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望穴肘。 院中可真熱鬧舔痕,春花似錦、人聲如沸伯复。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽丈积。三九已至,卻和暖如春债鸡,著一層夾襖步出監(jiān)牢的瞬間江滨,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工厌均, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留唬滑,地道東北人。 一個月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓棺弊,卻偏偏與公主長得像晶密,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子模她,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,700評論 2 354

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,324評論 0 10
  • 文|談小妍 (一)想法很豐滿稻艰,做法很骨干 有時候,我們工作壓力太大侈净,晚上加班到很晚尊勿,明明很疲勞...
    談小妍呀閱讀 406評論 0 2
  • 白頭何來憂,放眼若云浮畜侦。 附勢難自立元扔,趨炎多逐流。 人言好渾濁旋膳,哀歌豈解愁澎语。 貧賤無輕重,布衣笑王侯。 高懷當(dāng)殊世...
    智慧子閱讀 722評論 3 24