This chapter covers the basic setup for using this library.
- 本章介绍使用此库的基本设置。
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.
- 首先,将此库的依赖项添加到项目中。 如何执行此操作在此存储库的用法部分中进行了描述。 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,Fragment或其他内容中检索它:
// 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):
- 或者在代码中创建它(然后将其添加到布局中):
// 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
- 添加数据
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.
- 拥有图表实例后,您可以创建数据并将其添加到图表中。 此示例使用LineChart,其中Entry类表示图表中具有x和y坐标的单个条目。 其他图表类型(例如BarChart)为此目的使用其他类(例如BarEntry)。
To add data to your chart, wrap each data object you have into an Entry object, like below:
- 要向图表添加数据,请将您拥有的每个数据对象包装到Entry对象中,如下所示:
YourData[] dataObjects = ...;
List entries = new ArrayList();
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
- 下一步,您需要将创建的List
添加到LineDataSet对象。 DataSet对象保存属于一起的数据,并允许对该数据进行单独设计。 以下使用的“标签”仅具有描述性目的,并在图例中显示(如果已启用)。
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:
- 最后一步,您需要将创建的LineDataSet对象(或多个对象)添加到LineData对象。 此对象包含由Chart实例表示的所有数据,并允许进一步样式化。 创建数据对象后,您可以将其设置为图表并刷新它:
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.
- 请考虑上面的场景一个非常基本的设置。 有关更详细的说明,请参阅设置数据部分,其中说明了如何根据示例将数据添加到各种图表类型。
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.
- 有关图表表面和数据的设置和样式的信息,请访问常规设置和样式部分。 有关各个图表类型的更具体的样式和设置,请查看特定设置和样式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.
- 该库允许您完全自定义与图表视图的可能触摸(和手势)交互,并通过回调方法对交互作出反应。
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):如果设置为true,则启用缩放缩放。 如果禁用,则可以单独缩放x轴和y轴。
-
setDoubleTapToZoomEnabled(boolean enabled)
: Set this to false to disallow zooming the chart via double-tap on it.- setDoubleTapToZoomEnabled(boolean enabled):将此值设置为false以禁止通过双击来缩放图表。
Chart fling / deceleration
- 图表fling /减速
-
setDragDecelerationEnabled(boolean enabled)
: If set to true, chart continues to scroll after touch up. Default: true.- setDragDecelerationEnabled(boolean enabled):如果设置为true,则图表会在触摸后继续滚动。 默认值: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):减速摩擦系数[0; 1]间隔,较高的值表示速度将缓慢下降,例如,如果设置为0,它将立即停止。 1是无效值,将自动转换为0.9999。
Highlighting Values
- 突出显示值
How to allow highlighting entries via tap-gesture and programmatically is described int the highlightning section.
- 如何允许通过点击手势和编程方式突出显示条目在突出显示部分中进行了描述。
Gesture callbacks
- 手势回调
The OnChartGestureListener will allow you to react to gestures made on the chart:
- OnChartGestureListener将允许您对图表上的手势做出反应:
public interface OnChartGestureListener {
/**
* Callbacks when a touch-gesture has started on the chart (ACTION_DOWN)
* 在图表上启动触摸手势时回调(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)
* 触摸手势在图表上结束时的回调(ACTION_UP,ACTION_CANCEL)
* @param me
* @param lastPerformedGesture
*/
void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture);
/**
* Callbacks when the chart is longpressed.
* 图表被长按时回调。
* @param me
*/
public void onChartLongPressed(MotionEvent me);
/**
* Callbacks when the chart is double-tapped.
* 双击图表时的回调。
* @param me
*/
public void onChartDoubleTapped(MotionEvent me);
/**
* Callbacks when the chart is single-tapped.
* 单击图表时的回调。
* @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.
* 当图表通过缩放缩放手势缩放/缩放时。
* @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.
* 通过拖动手势移动/翻译图表时的回调。
* @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:
- 只需让你的接收回调的类实现这个接口并将其设置为图表的监听器:
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.
- 本节重点介绍通过tap-gesture和基于发行版v3.0.0以编程方式突出显示图表中条目的主题。
Enabling / Disabling highlighting
- 启用/禁用突出显示
-
setHighlightPerDragEnabled(boolean enabled)
: Set this to true on yourChart
to allow highlighting per dragging over the chart surface when it is fully zoomed out. Default: true- setHighlightPerDragEnabled(boolean enabled):在图表上将此值设置为true,以便在完全缩小时在图表表面上进行每次拖动时突出显示。 默认值:true
-
setHighlightPerTapEnabled(boolean enabled)
: Set this to false on yourChart
to prevent values from being highlighted by tap gesture. Values can still be highlighted via drag or programmatically. Default: true- setHighlightPerTapEnabled(boolean enabled):在图表上将此设置为false,以防止通过点按手势突出显示值。 仍可通过拖动或以编程方式突出显示值。 默认值: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):设置dp中的最大高光距离。 在图表上轻敲远离条目的距离不会触发突出显示。 默认值: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以撤消所有突出显示。 布尔标志确定应该调用选择侦听器还是不调用选择侦听器。
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以撤消所有突出显示。 布尔标志确定应该调用选择侦听器还是不调用选择侦听器。
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 []数组所表示的值。 提供null或空数组以撤消所有突出显示。
getHighlighted(): Returns an Highlight[] array that contains information about all highlighted entries, their x-index and dataset-index.
- getHighlighted():返回一个Highlight []数组,其中包含有关所有突出显示的条目,x-index和dataset-index的信息。
Selection callbacks
- 选择回调
This library provides a number of listeners for callbacks upon interaction. One of them is the OnChartValueSelectedListener, for callbacks when highlighting values via touch:
- 该库在交互时为回调提供了许多侦听器。 其中一个是OnChartValueSelectedListener,用于通过touch突出显示值时的回调:
public interface OnChartValueSelectedListener {
/**
* Called when a value has been selected inside the chart.
* 在图表中选择值时调用。
* @param e The selected Entry.
* @param h The corresponding highlight object that contains information
* about the highlighted position
* 相应的突出显示对象,包含有关突出显示位置的信息
*/
public void onValueSelected(Entry e, Highlight h);
/**
* Called when nothing has been selected or an "un-select" has been made.
* 在未选择任何内容或已取消“取消选择”时调用。
*/
public void onNothingSelected();
}
Simply let your class that should receive the callbacks implement this interface and set it as a listener to the chart:
- 只需让你的接收回调的类实现这个接口并将其设置为图表的监听器:
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关联的所有数据,例如突出显示的Entry对象本身,它所属的DataSet,它在绘图表面上的位置等等。 它可用于获取有关已突出显示的条目的信息,或用于向图表提供要突出显示的条目的信息。 关于这个目的,Highlight类提供了两个构造函数:
/** constructor for standard highlight */
// 标准高亮的构造函数
public Highlight(float x, int dataSetIndex) { ... }
/** constructor for stacked BarEntry highlight */
// 堆叠BarEntry高亮显示的构造函数
public Highlight(float x, int dataSetIndex, int stackIndex) { ... }
These constructors can be used to create a Highlight object which allows to perform highlighting programmatically:
- 这些构造函数可用于创建Highlight对象,该对象允许以编程方式执行突出显示:
// highlight the entry and x-position 50 in the first (0) DataSet
// 突出显示第一个(0)数据集中的条目和x位置50
Highlight highlight = new Highlight(50f, 0);
chart.highlightValue(highlight, false); // highlight this value, don't call listener
// 突出显示此值,不要调用侦听器
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:
- 高亮手势形式的所有用户输入都由默认的ChartHighlighter类在内部处理。 可以使用以下方法用自定义实现替换默认的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):为图表设置自定义highligher对象,以处理/处理在图表视图上执行的所有高光触摸事件。 您的自定义荧光笔对象需要扩展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页面侧重于AxisBase类,XAxis(XAxis)和YAxis(YAxis)的基类。 在v2.0.0中引入
The following methods mentioned below can be applied to both axes.
- 以下提到的方法可以应用于两个轴。
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
- 标签(以垂直(y轴)或水平(x轴)对齐绘制),包含轴描述值
-
A so called "axis-line" that is drawn directly next to and parallel to the labels
- 所谓的“轴线”,直接绘制在标签旁边并与之平行
-
The "grid-lines", each originating from an axis-label in horizontal direction
- “网格线”,每个都来自水平方向的轴标签
-
LimitLines
, that allow to present special infomation, like borders or constraints- LimitLines,允许提供特殊信息,如边框或约束
Control which parts (of the axis) should be drawn
- 控制应绘制哪些部分(轴)
-
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):设置启用或禁用的轴。 如果禁用,则无论其他任何设置如何,都不会绘制轴的任何部分。
-
setDrawLabels(boolean enabled)
: Set this to true to enable drawing the labels of the axis.- setDrawLabels(boolean enabled):将此属性设置为true以启用绘制轴标签。
-
setDrawAxisLine(boolean enabled)
: Set this to true if the line alongside the axis (axis-line) should be drawn or not.- setDrawAxisLine(boolean enabled):如果应该绘制沿轴(轴线)的线,则将其设置为true。
-
setDrawGridLines(boolean enabled)
: Set this to true to enable drawing the grid lines for the axis.- setDrawGridLines(boolean enabled):将此属性设置为true以启用绘制轴的网格线。
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):为此轴设置自定义最大值。如果设置,则不会根据提供的数据自动计算该值。
-
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():调用此方法以撤消先前设置的最大值。通过这样做,您将再次允许轴自动计算它的最大值。
-
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):为此轴设置自定义最小值。如果设置,则不会根据提供的数据自动计算该值。
-
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():调用此方法以撤消先前设置的最小值。通过这样做,您将再次允许轴自动计算它的最小值。
-
setStartAtZero(boolean enabled)
: Deprecated - UsesetAxisMinValue(...)
orsetAxisMaxValue(...)
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):如果设置为true,则此轴将被反转,这意味着最高值将位于底部,最低值将位于顶部。
-
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):设置图表中最高值的顶部间距(以总轴 - 范围的百分比表示)与轴上的最高值进行比较。
-
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):设置图表中最低值的底部间距(以总轴 - 范围的百分比表示)与轴上的最低值进行比较。
-
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):如果启用,此轴将仅显示其最小值和最大值。这将忽略/覆盖定义的标签计数(如果不强制)。
-
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):设置y轴的标签数。请注意,此数字不是固定的(如果force == false),并且只能近似。如果强制启用(true),则绘制精确指定的标签计数 - 这可能导致轴上的数字不均匀。
-
setPosition(YAxisLabelPosition pos)
: Sets the position where the axis-labels should be drawn. Either INSIDE_CHART or OUTSIDE_CHART.- setPosition(YAxisLabelPosition pos):设置应绘制轴标签的位置。 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):设置y轴值之间的最小间隔。这可以用于避免在放大到为轴设置的小数位数不再允许区分两个轴值的点时重复值。
-
setGranularityEnabled(boolean enabled)
: Enables the granularity feature that limits the interval of the y-axis when zooming in. Default: false- setGranularityEnabled(boolean enabled):启用粒度特征,在放大时限制y轴的间隔。默认值:false
Styling / modifying the axis
- 造型/修改轴
-
setTextColor(int color)
: Sets the color of the axis labels.- setTextColor(int color):设置轴标签的颜色。
-
setTextSize(float size)
: Sets the text-size of the axis labels in dp.- setTextSize(float size):以dp为单位设置轴标签的文本大小。
-
setTypeface(Typeface tf)
: Sets a customTypeface
for the axis labels.- setTypeface(Typeface tf):为轴标签设置自定义字体。
-
setGridColor(int color)
: Sets the color of the grid-lines of this axis.- setGridColor(int color):设置此轴的网格线的颜色。
-
setGridLineWidth(float width)
: Sets the width of the grid-lines of this axis.- setGridLineWidth(float width):设置此轴的网格线的宽度。
-
setAxisLineColor(int color)
: Sets the color of the axis-line of this axis.- setAxisLineColor(int color):设置此轴的轴线颜色。
-
setAxisLineWidth(float width)
: Sets the width of the axis-line of this axis.- setAxisLineWidth(float width):设置此轴的轴线宽度。
-
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):使网格线以虚线模式绘制,例如: 像这样 ”- - - - - -”。 “lineLength”控制线条的长度,“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接口,此处将对此进行说明。 您可以使用axis.setValueFormatter(IAxisValueFormatter formatter)方法将自定义格式化程序设置为轴。
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,它允许提供特殊信息,如边界或约束。 添加到YAxis的LimitLines在水平方向上绘制,在添加到XAxis时在垂直方向上绘制。 这是您从轴添加和删除LimitLines的方法:
-
addLimitLine(LimitLine l)
: Adds a newLimitLine
to this axis.- addLimitLine(LimitLine l):向此轴添加新的LimitLine。
-
removeLimitLine(LimitLine l)
: Removes the
specifiedLimitLine
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 theLimitLines
and the actual data. If this is set to true, theLimitLines
are drawn behind the actual data, otherwise on top. Default: false- setDrawLimitLinesBehindData(boolean enabled):允许控制LimitLines和实际数据之间的z顺序。 如果将此值设置为true,则会在实际数据后面绘制LimitLines,否则将在顶部绘制。 默认值: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.
- 例如,您的图表可能会显示用户使用应用程序记录的各种血压测量结果。 为了告知用户收缩压超过140 mmHg被认为是健康风险,您可以在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之前的版本中称为),是与水平轴相关的所有内容的数据和信息容器。 每个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
- 所谓的“轴线”,直接绘制在标签旁边并与之平行
- The "grid-lines", each originating from an axis-label in vertical direction
- “网格线”,每个都来自垂直方向的轴标签
In order to acquire an instance of the XAxis
class, do the following:
- 要获取XAxis类的实例,请执行以下操作:
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):设置绘制x轴标签的角度(以度为单位)。
-
setPosition(XAxisPosition pos)
: Sets the position where theXAxis
should appear. Choose between TOP, BOTTOM, BOTH_SIDED, TOP_INSIDE or BOTTOM_INSIDE.- setPosition(XAxisPosition pos):设置XAxis应出现的位置。 选择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的版本中称为)是与垂直轴相关的所有内容的数据和信息容器。 每个Line-,Bar-,Scatter或CandleStickChart都有一个左右YAxis对象,分别负责左轴或右轴。 RadarChart只有一个YAxis。 默认情况下,图表的两个轴都已启用并将被绘制。
In order to acquire an instance of the YAxis
class, call one of the following methods:
- 要获取YAxis类的实例,请调用以下方法之一:
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()
来确定此轴表示的图表的一侧。
Customizations that affect the value range of the axis need to be applied before setting data for the chart.
- 在为图表设置数据之前,需要应用影响轴值范围的自定义。
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.
- 默认情况下,添加到图表的所有数据都会绘制在图表的左侧YAxis上。 如果未进一步指定和启用,则调整右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:
- 如果您的图表需要支持不同的轴刻度,您可以通过设置数据应绘制的轴来实现。 这可以通过更改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上沿着每个值水平起源的网格线之外,还有所谓的零点,它在轴上的零(0)值处绘制,并且类似于网格线但可以单独配置。
-
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):设置零线的行宽。
-
setZeroLineColor(int color)
: Sets the color the zero-line should have.- setZeroLineColor(int color):设置零线应具有的颜色。
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.
- 上面的代码将产生如下图所示的零线。 不绘制轴值,不绘制网格线或轴线,只绘制零线。
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.
- 本章介绍了为各种图表设置数据的主题。
LineChart
If you want to add values (data) to the chart, it has to be done via the
- 如果要将值(数据)添加到图表中,则必须通过
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)类封装了呈现期间图表所需的所有数据和信息。 对于每种类型的图表,都存在ChartData的不同子类(例如LineData),应该用于设置图表的数据。 在构造函数中,您可以移交List <? 将IDataSet>扩展为要显示的值。 下面是LineData类(扩展ChartData)的示例,它用于向LineChart添加数据:
/** List constructor */
public LineData(List 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对象表示图表内属于一起的一组条目(例如,类条目)。 它旨在逻辑上分离图表中的不同值组。 对于每种类型的图表,存在扩展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中显示一年内两家不同公司的季度收入。 在这种情况下,建议创建两个不同的LineDataSet对象,每个对象包含四个值(每个季度一个)。
Of course, it is also possible to provide just one LineDataSet object containing all 8 values for the two companys.
- 当然,也可以只提供一个包含两个公司的所有8个值的LineDataSet对象。
So how to setup a LineDataSet object?
- 那么如何设置LineDataSet对象呢?
public LineDataSet(List 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.
- 在查看构造函数(不同的构造函数可用)时,可以看到LineDataSet需要一个类型为Entry的List和一个用于描述LineDataSet的String以及一个用于Legend的标签。 此外,此标签可用于在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:
- 首先,创建将保存您的值的Entry类型列表:
List valsComp1 = new ArrayList();
List valsComp2 = new ArrayList();
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轴的正确索引。 (当然,这里可以使用循环,在这种情况下,循环的计数器变量可以是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:
- 现在我们有了Entry对象列表,可以创建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:
- 通过调用setAxisDependency(...),可以指定DataSet应绘制的轴。 最后但并非最不重要的是,我们创建了一个IDataSets列表并构建了我们的ChartData对象:
// use the interface ILineDataSet
List dataSets = new ArrayList();
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.
- 调用invalidate()后,将刷新图表并绘制提供的数据。
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之间的数字),我们可以通过使用IAxisValueFormatter接口来实现。 此界面允许自定义XAxis上绘制的值的样式。 在此示例中,formatter可能如下所示:
// the labels that should be drawn on the XAxis
// 应该在XAxis上绘制的标签
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
// 我们不绘制数字,因此不需要十进制数字
@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.
- 有关IAxisValueFormatter接口的详细信息,请参见此处。
If additional styling is applied, the LineChart
resulting from this example should look similar to the one below:
- 如果应用了其他样式,则此示例生成的LineChart应类似于下面的样式:
Setting data for normal BarChart
, ScatterChart
, BubbleChart
and CandleStickChart
works similar to the LineChart
. A special case is the BarChart
with multiple (grouped) bars, which will be explained below.
- 设置正常BarChart,ScatterChart,BubbleChart和CandleStickChartworks的数据类似于LineChart。 一个特例是带有多个(分组)条形的BarChart,下面将对此进行说明。
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 List
of Entry
objects can be sorted manually or using the EntryXComparator
:
- 请注意,此库不正式支持从条目列表中绘制LineChart数据,而不是按条目的x位置按升序排序。 以未分类的方式添加条目可能会导致正确绘制,但也可能导致意外行为。 可以手动或使用EntryXComparator对Listof Entry对象进行排序:
List 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.
- 之所以需要这样做是因为该库使用二进制搜索算法以获得更好的性能,仅用于排序列表。
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设置数据的方式与LineChart非常相似。 主要区别是需要用于设置数据的数据对象(例如BarEntry而不是Entry)。 除此之外,BarChart还有不同的造型选择。
Consider the following example of filling a BarChart with data:
- 请考虑以下使用数据填充BarChart的示例:
List 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:
- 在上面的示例中,创建了五个BarEntry对象并将其添加到BarDataSet。 请注意,第四个和第五个条目之间的x位置存在“2”的间隙。 在此示例中,此间隙用于解释BarChart中柱的定位如何工作。 本教程末尾的屏幕截图将显示给定数据的结果BarChart。 下一步,需要创建一个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.
- 在上面的代码片段中,创建了一个BarData对象。 当创建图表的BarEntry对象时,我们在每个条形(中心)之间的x轴上留下了“1f”的空间。 通过将条宽设置为0.9f,我们有效地在每个条之间创建0.1f的空间。 setFitBars(true)调用将告诉图表调整它的x轴值范围以完全适合所有条形,并且两侧不会切断条形。
After creating the BarData object, we set it to the chart and refresh. The result should look close to the one shown below:
- 创建BarData对象后,我们将其设置为图表并刷新。 结果应该看起来接近下面显示的结果:
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:
- 本节将重点介绍显式分组BarChart,这意味着库将处理条形的x位置。 请考虑以下示例设置:
YourData[] group1 = ...;
YourData[] group2 = ...;
List entriesGroup1 = new ArrayList<>();
List 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位置无关紧要。 基于条目列表中BarEntry的位置执行分组。
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(...)方法执行两个BarDataSet对象的分组。 该方法采用以下参数:
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参数确定分组条应该从XAxis开始的位置(在本例中为“1980”),groupSpace确定每组条之间留下的空间,barSpace确定组中各个条之间的间距。 基于这些参数,groupBars(...)方法将XAxis上每个条形的位置改变为分组外观,从而保留各个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参数以及barWidth定义。
The result should look somewhat like this:
- 结果应该看起来像这样:
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.
- 当然,通过简单地手动将各个条正确地放置在XAxis上,也可以在不使用groupBars(...)方法的情况下实现分组的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的标签位于组上方,如上面的屏幕截图所示,您可以使用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设置与普通的BarChart完全相似,但创建单个BarEntry对象的方式除外。 如果是堆叠条形,则必须使用BarEntry的不同构造函数:
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:
- 此构造函数允许提供多个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对象的形式获取数据。 这些对象的构造函数如下所示:
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:
- 构造函数的第一个参数用于实际的“值”,应该在PieChart中将其绘制为饼图。 名为“label”的第二个String参数用于提供切片的其他描述。 请考虑以下示例PieChart设置:
List 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与上面使用的数据可能类似于: