二、Charts

8. Setting Colors

Since release v1.4.0, the ColorTemplate object that was responsible for setting colors in previous releases is no longer needed (deprecated). Nevertheless, it still holds all predefined color arrays (e.g. ColorTemplate.VORDIPLOM_COLORS and provides convenience methods for transforming colors from the resources (resource integers) into "real" colors.

  • 从版本v1.4.0开始,不再需要(不建议使用)负责在先前版本中设置颜色的ColorTemplate对象。 尽管如此,它仍然保留了所有预定义的颜色数组(例如ColorTemplate.VORDIPLOM_COLORS,并提供了方便的方法,用于将颜色从资源(资源整数)转换为“真实”颜色。

Instead of the ColorTemplate, colors can now be specified directly via DataSet object, which allows separate styling for each DataSet.

  • 现在可以通过DataSet对象直接指定颜色而不是ColorTemplate,这允许为每个DataSet单独设置样式。

In this short example, we have our two different LineDataSet objects representing the quarterly revenues of two companies (previously mentioned in the Setting Data tutorial), for which we now want to set different colors.

  • 在这个简短的例子中,我们有两个不同的LineDataSet对象,代表两家公司的季度收入(之前在设置数据教程中提到过),我们现在想要设置不同的颜色。

What we want:

  • 我们想要什么:
  • the values of "Company 1" should be represented by four different variations of the color "red"

    • “公司1”的值应由“红色”的四种不同变体表示
  • the values of "Company 2" should be represented by four different variations of the color "green"

    • “公司2”的值应由“绿色”颜色的四种不同变体表示

This is what the code looks like:

  • 这就是代码的样子:
LineDataSet setComp1 = new LineDataSet(valsComp1, "Company 1");
  // sets colors for the dataset, resolution of the resource name to a "real" color is done internally
  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);

Besides that, there are many other ways for setting colors for a DataSet. Here is the full documentation:

  • 除此之外,还有许多其他方法可以为DataSet设置颜色。这是完整的文档:

setColors(int [] colors, Context c): Sets the colors that should be used fore this DataSet. Colors are reused as soon as the number of Entries the DataSet represents is higher than the size of the colors array. You can use "new int[] { R.color.red, R.color.green, ... }" to provide colors for this method. Internally, the colors are resolved using getResources().getColor(...).

  • setColors(int [] colors,Context c):设置在此DataSet之前应该使用的颜色。只要DataSet表示的条目数高于colors数组的大小,就会重复使用颜色。您可以使用“new int [] {R.color.red,R.color.green,...}”为此方法提供颜色。在内部,使用getResources()。getColor(...)解析颜色。

setColors(int [] colors): Sets the colors that should be used fore this DataSet. Colors are reused as soon as the number of Entries the DataSet represents is higher than the size of the colors array. Make sure that the colors are already prepared (by calling getResources().getColor(...)) before adding them to the DataSet.

  • setColors(int [] colors):设置在此DataSet之前应使用的颜色。只要DataSet表示的条目数高于colors数组的大小,就会重复使用颜色。在将它们添加到DataSet之前,请确保已准备好颜色(通过调用getResources()。getColor(...))。

setColors(ArrayList<Integer> colors): Sets the colors that should be used fore this DataSet. Colors are reused as soon as the number of Entries the DataSet represents is higher than the size of the colors array. Make sure that the colors are already prepared (by calling getResources().getColor(...)) before adding them to the DataSet.

  • setColors(ArrayList <Integer> colors):设置在此DataSet之前应使用的颜色。只要DataSet表示的条目数高于colors数组的大小,就会重复使用颜色。在将它们添加到DataSet之前,请确保已准备好颜色(通过调用getResources()。getColor(...))。

setColor(int color): Sets the one and ONLY color that should be used for this DataSet. Internally, this recreates the colors array and adds the specified color.
setColor(int color):设置应该用于此DataSet的一种颜色和唯一颜色。在内部,这将重新创建颜色数组并添加指定的颜色。

ColorTemplate example:

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

If no colors are set for a DataSet, default colors are used.

  • 如果没有为DataSet设置颜色,则使用默认颜色。

The ValueFormatter interface

Available since v1.6.2 - changed (improved) in v2.1.4

  • 自v1.6.2起可用 - 在v2.1.4中更改(改进)

The IValueFormatter interface can be used to create custom-made formatter classes that allow to format values within the chart (from DataSets) in a specific way before drawing them.

  • IValueFormatter接口可用于创建自定义格式化程序类,允许在绘制图表之前以特定方式格式化图表中的值(来自DataSet)。

For using the IValueFormatter, simply create a new class and let it implement the interface and return whatever you want to be displayed from the getFormattedValue(...) method.

  • 要使用IValueFormatter,只需创建一个新类,让它实现接口并从getFormattedValue(...)方法返回您想要显示的内容。

Creating a Formatter

public class MyValueFormatter implements IValueFormatter {

    private DecimalFormat mFormat;
    
    public MyValueFormatter() {
        mFormat = new DecimalFormat("###,###,##0.0"); // use one decimal
    }
    
    @Override
    public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
        // write your logic here
        return mFormat.format(value) + " $"; // e.g. append a dollar-sign
    }
}

Then, set your formatter to the ChartData or DataSet object:

  • 然后,将您的格式化程序设置为ChartData或DataSet对象:
// usage on whole data object  用于整个数据对象
lineData.setValueFormatter(new MyValueFormatter());

// usage on individual dataset object 用于单个数据集对象
lineDataSet.setValueFormatter(new MyValueFormatter());

Predefined Formatters

  • 预定义的格式化程序
  • LargeValueFormatter: Can be used for formatting large values > "1.000". It will turn values like "1.000" into "1k", "1.000.000" will be "1m" (million), "1.000.000.000" will be "1b" (billion) and values like one trillion will be e.g. "1t".

    • LargeValueFormatter:可用于格式化大值>“1.000”。 它将诸如“1.000”的值变为“1k”,“1.000.000”将变为“1m”(百万),“1.000.000.000”将变为“1b”(十亿),并且例如一万亿的值将是例如“1吨”。
  • PercentFormatter: Used for displaying a "%" sign after each value with 1 decimal digit. Especially useful for the PieChart. 50 -> 50.0 %

    • PercentFormatter:用于在每个值后面显示“%”符号,带有1个十进制数字。 对PieChart尤其有用。 50 - > 50.0%
  • StackedValueFormatter: A formatter specifically designed to be used with stacked BarChart. It allows to specify whether all stack values should be drawn or just the top value.

    • StackedValueFormatter:专门设计用于堆叠BarChart的格式化程序。 它允许指定是应绘制所有堆栈值还是仅绘制最高值。

The AxisValueFormatter interface

  • AxisValueFormatter接口

Introduced in release v3.0.0, this interface allows the custom styling of both XAxis and YAxisvalues before drawing.

  • 该版本在v3.0.0版本中引入,允许在绘制之前自定义样式化XAxis和YAxisvalues。

Creating a Formatter

  • 创建格式化程序

All that needs to be done to custom-format values on the axis is to create a class that implements the IAxisValueFormatter interface, as shown below. This formatter is used to format the values of an axis to 1 decimal digit always.

  • 所有需要对轴上的自定义格式值进行的操作是创建一个实现IAxisValueFormatter接口的类,如下所示。 此格式化程序用于始终将轴的值格式化为1个十进制数。
public class MyYAxisValueFormatter implements IAxisValueFormatter {

    private DecimalFormat mFormat;

    public MyAxisValueFormatter() {

        // format values to 1 decimal digit
        mFormat = new DecimalFormat("###,###,##0.0");
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // "value" represents the position of the label on the axis (x or y)
        return mFormat.format(value) + " $";
    }
    
    /** this is only needed if numbers are returned, else return 0 */
    @Override
    public int getDecimalDigits() { return 1; }
}

The example below shows how to plot values from a String[] array to the axis:

  • 下面的示例显示如何将String []数组中的值绘制到轴:
public class MyXAxisValueFormatter implements IAxisValueFormatter {

    private String[] mValues;

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

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // "value" represents the position of the label on the axis (x or y)
        return mValues[(int) value];
    }
    
    /** this is only needed if numbers are returned, else return 0 */
    @Override
    public int getDecimalDigits() { return 0; }
}

Setting the Formatter

  • 设置格式化程序

After the creation of the formatter, simply set it to your axis of choice:

  • 创建格式化程序后,只需将其设置为您选择的轴:
YAxis left = chart.getAxisLeft();
left.setValueFormatter(new MyYAxisValueFormatter());

String[] values = new String[] { ... };

XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new MyXAxisValueFormatter(values));

Instead of the default values ranging from axis minimum value to axis maximum value, the axis will now plot the data specified by the formatter.

  • 现在,轴将绘制格式化程序指定的数据,而不是从轴最小值到轴最大值的默认值。

Restricting Intervals

  • 限制间隔

In case you are using a formatter based on array indices (like above), it makes sense to restrict the minimum interval of your axis to "1":

  • 如果您使用基于数组索引的格式化程序(如上所述),则将轴的最小间隔限制为“1”是有意义的:

This will prevent the formatter from drawing duplicate axis labels (caused by axis intervals < 1). As soon as the "zoom level" of the chart is high enough, it will stop recalculating smaller intervals.

  • 这将防止格式化程序绘制重复的轴标签(由轴间隔<1引起)。 只要图表的“缩放级别”足够高,它就会停止重新计算较小的间隔。

Predefined Formatters

  • 预定义的格式化程序
  • LargeValueFormatter: Can be used for formatting large values > "1.000". It will turn values like "1.000" into "1k", "1.000.000" will be "1m" (million), "1.000.000.000" will be "1b" (billion) and values like one trillion will be e.g. "1t".
    • LargeValueFormatter:可用于格式化大值>“1.000”。 它将诸如“1.000”的值变为“1k”,“1.000.000”将变为“1m”(百万),“1.000.000.000”将变为“1b”(十亿),并且例如一万亿的值将是例如“1吨”。
  • PercentFormatter: Used for displaying a "%" sign after each value with 1 decimal digit. Especially useful for the PieChart. 50 -> 50.0 %
    • PercentFormatter:用于在每个值后面显示“%”符号,带有1个十进制数字。 对PieChart尤其有用。 50 - > 50.0%

Example Formatters

  • 示例格式化程序
  • DayAxisValueFormatter: This formatter converts the provided value to plot into a date String, altering the string depending on scale.
    • DayAxisValueFormatter:此格式化程序将提供的值转换为日期字符串,根据比例更改字符串。
      遗留格式化程序

Legacy Formatters

  • 遗留格式化程序

Prior to release v3.0.0, there were separate formatters for XAxis and YAxis. The documentation for these formatters can be found here:

  • 在发布v3.0.0之前,XAxis和YAxis有单独的格式化程序。 这些格式化程序的文档可以在这里找到:

11. General Settings & Styling

This section focuses on settings and styling of this library applicable for all Chart types.

Refreshing

  • 清爽
  • invalidate(): Calling this method on the chart will refresh (redraw) it. This is needed in order to make changes performed on the chart take effect.
    • invalidate():在图表上调用此方法将刷新(重绘)它。 为了使图表上执行的更改生效,需要这样做。
  • notifyDataSetChanged(): Lets the chart know it's underlying data has changed and performs all necessary recalculations (offsets, legend, maxima, minima, ...). This is needed especially when adding data dynamically.
    • notifyDataSetChanged():让图表知道它的基础数据已经改变并执行所有必要的重新计算(偏移,图例,最大值,最小值,......)。 特别是在动态添加数据时需要这样做。

Logging

  • 记录
  • setLogEnabled(boolean enabled): Setting this to true will activate chart logcat output. Enabling this is bad for performance, keep disabled if not necessary.
    • setLogEnabled(boolean enabled):将此设置为true将激活图表logcat输出。 启用此功能对性能有害,如果不必要,请禁用。

General Chart Styling

  • 一般图表样式

Here are some general styling methods you can directly use on the chart:

  • 以下是您可以在图表上直接使用的一些通用样式方法:
  • setBackgroundColor(int color): Sets the background color that will cover the whole chart-view. In addition, a background-color can be set via .xml in the layout file.
    • setBackgroundColor(int color):设置将覆盖整个图表视图的背景颜色。 此外,可以通过布局文件中的.xml设置背景颜色。
  • setDescription(String desc): Set a description text that appears in the bottom right corner of the chart.
    • setDescription(String desc):设置显示在图表右下角的描述文本。
  • setDescriptionColor(int color): Sets the color of the description text.
    • setDescriptionColor(int color):设置描述文本的颜色。
  • setDescriptionPosition(float x, float y): Sets a custom position for the description text in pixels on the screen.
    • setDescriptionPosition(float x,float y):在屏幕上以像素为单位设置描述文本的自定义位置。
  • setDescriptionTypeface(Typeface t): Sets the Typeface used for drawing the description text.
    • setDescriptionTypeface(Typeface t):设置用于绘制描述文本的字体。
  • setDescriptionTextSize(float size): Sets the size of the description text in pixels, min 6f, max 16f.
    • setDescriptionTextSize(float size):设置描述文本的大小,以像素为单位,最小为6f,最大为16f。
  • setNoDataText(String text): Sets the text that should appear if the chart is empty.
    • setNoDataText(String text):设置图表为空时应显示的文本。
  • setDrawGridBackground(boolean enabled): If enabled, the background rectangle behind the chart drawing-area will be drawn.
    • setDrawGridBackground(boolean enabled):如果启用,将绘制图表绘图区域后面的背景矩形。
  • setGridBackgroundColor(int color): Sets the color the grid-background should be drawn with.
    • setGridBackgroundColor(int color):设置应该使用网格背景绘制的颜色。
  • setDrawBorders(boolean enabled): Enables / disables drawing the chart borders (lines surrounding the chart).
    • setDrawBorders(boolean enabled):启用/禁用绘制图表边框(图表周围的线条)。
  • setBorderColor(int color): Sets the color of the chart border lines.
    • setBorderColor(int color):设置图表边框线的颜色。
  • setBorderWidth(float width): Sets the width of the chart border lines in dp.
    • setBorderWidth(float width):以dp为单位设置图表边框线的宽度。
  • setMaxVisibleValueCount(int count): Sets the number of maximum visible drawn value-labels on the chart. This only takes affect when setDrawValues() is enabled.
    • setMaxVisibleValueCount(int count):设置图表上最大可见绘制值标签的数量。 这仅在启用setDrawValues()时生效。

12. Specific Settings & Styling

In chapter 1. Getting Started general chart settings and styling methods applicable for all chart types were mentioned. This chapter focuses on specific settings for the individual chart types.

  • 在第1章中,提到了适用于所有图表类型的常规图表设置和样式方法。 本章重点介绍各个图表类型的特定设置。

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

  • Line-,Bar-,Scatter-,Candle-和BubbleChart
  • setAutoScaleMinMaxEnabled(boolean enabled): Flag that indicates if auto scaling on the y axis is enabled. If enabled the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes. This is especially interesting for charts displaying financial data. Default: false

    • setAutoScaleMinMaxEnabled(boolean enabled):指示是否启用y轴自动缩放的标志。 如果启用,则只要视口更改,y轴就会自动调整为当前x轴范围的最小和最大y值。 这对于显示财务数据的图表尤其有用。 默认值:false
  • setKeepPositionOnRotation(boolean enabled): Sets wether the chart should keep its position (zoom / scroll) after orientation change. Default: false

    • setKeepPositionOnRotation(boolean enabled):设置方向更改后图表应保持其位置(缩放/滚动)。 默认值:false

BarChart

  • setDrawValueAboveBar(boolean enabled): If set to true, all values are drawn above their bars, instead of below their top.

    • setDrawValueAboveBar(boolean enabled):如果设置为true,则所有值都会在其条形图上方绘制,而不是在其顶部之下。
  • setDrawBarShadow(boolean enabled): If set to true, a grey area is drawn behind each bar that indicates the maximum value. Enabling his will reduce performance by about 40%.

    • setDrawBarShadow(boolean enabled):如果设置为true,则在每个条形后面绘制一个灰色区域,指示最大值。 启用他的功能会使性能降低约40%。
  • setDrawValuesForWholeStack(boolean enabled): If set to true, all values of stacked bars are drawn individually, and not just their sum on top of all.

    • setDrawValuesForWholeStack(boolean enabled):如果设置为true,则堆叠条形的所有值都是单独绘制的,而不仅仅是它们之和的总和。
  • setDrawHighlightArrow(boolean enabled): Set this to true to draw the highlightning arrow above each bar when highlighted.

    • setDrawHighlightArrow(boolean enabled):将此项设置为true可在突出显示时在每个条形图上方绘制突出显示箭头。

PieChart

  • setDrawSliceText(boolean enabled): Set this to true to draw the x-value text into the pie slices.

    • setDrawSliceText(boolean enabled):将此值设置为true可将x值文本绘制到饼图切片中。
  • setUsePercentValues(boolean enabled): If this is enabled, values inside the chart are drawn in percent and not with their original value. Values provided for the ValueFormatterto format are then provided in percent.

    • setUsePercentValues(boolean enabled):如果启用此选项,则图表中的值将以百分比形式绘制,而不是以其原始值绘制。 然后以百分比形式提供为ValueFormatterto格式提供的值。
  • setCenterText(SpannableString text): Sets the text that is drawn in the center of the PieChart. Longer text will be automatically "wrapped" to avoid clipping into the pie-slices.

    • setCenterText(SpannableString text):设置在PieChart中心绘制的文本。 较长的文本将自动“包装”以避免剪切到饼图切片中。
  • setCenterTextRadiusPercent(float percent): Sets the rectangular radius of the bounding box for the center text, as a percentage of the pie hole default 1.f (100%).

    • setCenterTextRadiusPercent(float percent):设置中心文本边界框的矩形半径,以饼图孔默认值1.f(100%)的百分比表示。
  • setHoleRadius(float percent): Sets the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart), default 50%

    • setHoleRadius(float percent):以最大半径的百分比(max =整个图表的半径)设置饼图中心的孔半径,默认为50%
  • setTransparentCircleRadius(float percent): Sets the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart), default 55% -> means 5% larger than the center-hole by default

    • setTransparentCircleRadius(float percent):设置在饼图中孔旁边绘制的透明圆的半径,以最大半径的百分比表示(max =整个图表的半径),默认为55% - >表示大于5% 默认为中心孔
  • setTransparentCircleColor(int color): Sets the color of the transparent circle.

    • setTransparentCircleColor(int color):设置透明圆的颜色。
  • setTransparentCircleAlpha(int alpha): Sets the amount of transparency (0-255) the transparent circle should have.

    • setTransparentCircleAlpha(int alpha):设置透明圆圈应具有的透明度(0-255)。
  • setMaxAngle(float maxangle): Sets the max angle that is used for calculating the pie-circle. 360f means it's a full PieChart, 180f results in a half-pie-chart. Default: 360f

    • setMaxAngle(float maxangle):设置用于计算饼圈的最大角度。 360f意味着它是一个完整的PieChart,180f会产生一个半饼图。 默认值:360f

RadarChart

  • RadarChart
  • setSkipWebLineCount(int count): Allows to skip web lines coming from the center of the chart. Especially useful if there are a lot of lines.
    • setSkipWebLineCount(int count):允许跳过来自图表中心的Web行。 如果有很多行,特别有用。

13. Legend

By default, all chart types support legends and will automatically generate and draw a legend after setting data for the chart. The Legend usually consists of multiple entries each represented by a label an a form/shape.

  • 默认情况下,所有图表类型都支持图例,并在设置图表数据后自动生成并绘制图例。 图例通常由多个条目组成,每个条目由标签和形状/形状表示。

The number of entries the automatically generated legend contains depends on the number of different colors (across all DataSet objects) as well as on the DataSet labels. The labels of the Legend depend on the labels set for the used DataSet objects in the chart. If no labels for the DataSet objects have been specified, the chart will automatically generate them. If multiple colors are used for one DataSet, those colors are grouped and only described by (belong to) one label.

  • 自动生成的图例包含的条目数取决于不同颜色的数量(跨所有DataSet对象)以及DataSet标签。 图例的标签取决于为图表中使用的DataSet对象设置的标签。 如果未指定DataSet对象的标签,则图表将自动生成它们。 如果一个DataSet使用多种颜色,则这些颜色被分组,并且仅由(属于)一个标签描述。

For customizing the Legend, use you can retreive the Legend object from the chart using the getLegend() method:

  • 要自定义图例,可以使用getLegend()方法从图表中检索Legend对象:
Legend legend = chart.getLegend();
Control if the legend should be drawn
  • 控制是否应绘制图例

setEnabled(boolean enabled): Sets the Legend enabled or disabled. If disabled, the Legend will not be drawn.

  • setEnabled(boolean enabled):设置启用或禁用图例。 如果禁用,则不会绘制图例。
Styling / modifying the legend
  • setEnabled(boolean enabled):设置启用或禁用图例。 如果禁用,则不会绘制图例。

setTextColor(int color): Sets the color of the legend labels.

  • setTextColor(int color):设置图例标签的颜色。

setTextSize(float size): Sets the text-size of the legend labels in dp.

  • setTextSize(float size):设置dp中图例标签的文本大小。

setTypeface(Typeface tf): Sets a custom Typeface for the legend labels.

  • setTypeface(Typeface tf):为图例标签设置自定义字体。
Wrapping / clipping avoidance
  • 避免缠绕/剪裁

setWordWrapEnabled(boolean enabled): If enabled, the content of the legend will not clip outside the charts bounds, but instead create a new line. Please note that this reduces performance and is only available for legends below the chart.

  • setWordWrapEnabled(boolean enabled):如果启用,图例的内容将不会在图表边界之外剪切,而是创建一个新行。 请注意,这会降低性能,仅适用于图表下方的图例。

setMaxSizePercent(float maxSize): Sets the maximum relative size out of the whole chart view in percent. Default: 0.95f (95%)

  • setMaxSizePercent(float maxSize):以百分比形式设置整个图表视图的最大相对大小。 默认值:0.95f(95%)
Customizing the legend
  • 自定义图例

setPosition(LegendPosition pos): Sets the LegendPosition which defines where the Legend should appear. Choose between RIGHT_OF_CHART, RIGHT_OF_CHART_CENTER, RIGHT_OF_CHART_INSIDE, BELOW_CHART_LEFT, BELOW_CHART_RIGHT, BELOW_CHART_CENTER or PIECHART_CENTER (PieChart only), ... and more.

  • setPosition(LegendPosition pos):设置LegendPosition,用于定义Legend应出现的位置。 选择RIGHT_OF_CHART,RIGHT_OF_CHART_CENTER,RIGHT_OF_CHART_INSIDE,BELOW_CHART_LEFT,BELOW_CHART_RIGHT,BELOW_CHART_CENTER或PIECHART_CENTER(仅限PieChart),......等等。

setForm(LegendForm shape): Sets the LegendForm that should be used. This is the shape that is drawn next to the legend-labels with the color of the DataSet the legend-entry represents. Choose between SQUARE, CIRCLE or LINE.

  • setForm(LegendForm shape):设置应该使用的LegendForm。 这是在图例标签旁边绘制的形状,其中包含图例条目所代表的DataSet的颜色。 在SQUARE,CIRCLE或LINE之间进行选择。

setFormSize(float size): Sets the size of the legend-forms in dp.

  • setFormSize(float size):设置dp中图例形式的大小。

setXEntrySpace(float space): Sets the space between the legend-entries on the horizontal axis.

  • setXEntrySpace(float space):设置水平轴上图例条目之间的间距。

setYEntrySpace(float space): Sets the space between the legend-entries on the vertical axis.

  • setYEntrySpace(float space):设置垂直轴上图例条目之间的间距。

setFormToTextSpace(float space): Sets the space between the legend-label and the corresponding legend-form.

  • setFormToTextSpace(float space):设置图例标签和相应图例表单之间的空格。

setWordWrapEnabled(boolean enabled): Should the legend word wrap? / this is currently supported only for BelowChartLeft, BelowChartRight, BelowChartCenter. / you may want to set maxSizePercent when word wrapping, to set the point where the text wraps.

  • setWordWrapEnabled(boolean enabled):图例文字是否应该换行? /目前仅支持BelowChartLeft,BelowChartRight,BelowChartCenter。 /你可能想在自动换行时设置maxSizePercent,以设置文本换行的点。
Setting custom labels & colors
  • 设置自定义标签和颜色

setCustom(int[] colors, String[] labels): Sets a custom legend's labels and colors arrays. The colors count should match the labels count. Each color is for the form drawn at the same index. A null label will start a group. A (-2) color will avoid drawing a form This will disable the feature that automatically calculates the legend labels and colors from the datasets. Call resetCustom() to re-enable automatic calculation (and then notifyDataSetChanged() is needed to auto-calculate the legend again)

  • setCustom(int [] colors,String [] labels):设置自定义图例的标签和颜色数组。 颜色计数应与标签数量匹配。 每种颜色用于在相同索引处绘制的表单。 空标签将启动一个组。 (-2)颜色将避免绘制表单这将禁用自动计算数据集中的图例标签和颜色的功能。 调用resetCustom()重新启用自动计算(然后需要notifyDataSetChanged()再次自动计算图例)

resetCustom(): Calling this will disable the custom legend labels (set by setCustom(...)). Instead, the labels will again be calculated automatically (after notifyDataSetChanged() is called).

  • resetCustom():调用此方法将禁用自定义图例标签(由setCustom(...)设置)。 相反,将再次自动计算标签(在调用notifyDataSetChanged()之后)。

setExtra(int[] colors, String[] labels): Sets colors and labels that will be appended to the end of the auto calculated colors and labels arrays after calculating the legend. (if the legend has already been calculated, you will need to call notifyDataSetChanged() to let the changes take effect)

  • setExtra(int [] colors,String [] labels):设置在计算图例后将附加到自动计算颜色和标签数组末尾的颜色和标签。 (如果已经计算了图例,则需要调用notifyDataSetChanged()以使更改生效)

Example

Legend l = chart.getLegend();
    l.setFormSize(10f); // set the size of the legend forms/shapes
    l.setForm(LegendForm.CIRCLE); // set what type of form/shape should be used
    l.setPosition(LegendPosition.BELOW_CHART_LEFT);
    l.setTypeface(...);
    l.setTextSize(12f);
    l.setTextColor(Color.BLACK);
    l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
    l.setYEntrySpace(5f); // set the space between the legend entries on the y-axis

    // set custom labels and colors
    l.setCustom(ColorTemplate.VORDIPLOM_COLORS, new String[] { "Set1", "Set2", "Set3", "Set4", "Set5" });

    // and many more...

14. Dynamic & Realtime Data

Getting started

MPAndroidChart does not offically support realtime data, however, for adding new data to the chart or removing data dynamically, there are various methods that allow to either add or remove Entry objects to an existing DataSet or DataSet objects to/from an existing ChartDataobject.

  • MPAndroidChart不会正式支持实时数据,但是,为了向图表添加新数据或动态删除数据,有多种方法可以向现有的ChartData对象添加或删除现有DataSet或DataSet对象的Entry对象。

Possibilities of adding / removing data dynamically

Class DataSet (and all subclasses):

  • addEntry(Entry e): Adds the given Entry object to the DataSet.
    • addEntry(Entry e):将给定的Entry对象添加到DataSet。
      ChartData类(和所有子类):
Class ChartData (and all subclasses):
  • 类DataSet(和所有子类):
  • addEntry(Entry e, int dataSetIndex): Adds the given Entry to the DataSet at the specified dataset index.
    • addEntry(Entry e,int dataSetIndex):将给定的Entry添加到指定数据集索引处的DataSet。
  • addDataSet(DataSet d): Adds the given DataSet object to the ChartData object.
    • addDataSet(DataSet d):将给定的DataSet对象添加到ChartData对象。

In addition to that, there are also methods for removing data dynamically:

  • 除此之外,还有一些动态删除数据的方法:
Class DataSet (and all subclasses):
  • public boolean removeFirst(): Removes the first Entry (at index 0) of this DataSet from the entries array. Returns true if successful, false if not.

    • public boolean removeFirst():从entries数组中删除此DataSet的第一个Entry(在索引0处)。 如果成功则返回true,否则返回false。
  • public boolean removeLast(): Removes the last Entry (at index size-1) of this DataSet from the entries array. Returns true if successful, false if not.

    • public boolean removeLast():从entries数组中删除此DataSet的最后一个Entry(索引大小为-1)。 如果成功则返回true,否则返回false。
  • public boolean removeEntry(Entry e): Removes the given Entry object from the DataSet. Returns true if successful.

    • public boolean removeEntry(Entry e):从DataSet中删除给定的Entry对象。 如果成功则返回true。
  • public boolean removeEntry(int xIndex): Removes the Entry at the given x-index from the DataSet. Returns true if successful.

    • public boolean removeEntry(int xIndex):从DataSet中删除给定x-index处的Entry。 如果成功则返回true。
Class ChartData (and all subclasses):
  • ChartData类(和所有子类):
  • public boolean removeEntry(Entry e, int dataSetIndex): Removes the given Entryobject from the DataSet with the given dataset index. Returns true if successful.

    • public boolean removeEntry(Entry e,int dataSetIndex):使用给定的数据集索引从DataSet中删除给定的Entry对象。 如果成功则返回true。
  • public boolean removeEntry(int xIndex, int dataSetIndex): Removes the Entry at the given x-index from the DataSet with the given dataset index. Returns true if successful.

    • public boolean removeEntry(int xIndex,int dataSetIndex):使用给定的数据集索引从DataSet中移除给定x-index处的Entry。 如果成功则返回true。
  • public boolean removeDataSet(DataSet d): Removes the given DataSet object from the ChartData object. Returns true if successful.

    • public boolean removeDataSet(DataSet d):从ChartData对象中删除给定的DataSet对象。 如果成功则返回true。
  • public boolean removeDataSet(int index): Removes the DataSet at the given index from the ChartData object. Returns true if successful.

    • public boolean removeDataSet(int index):从ChartData对象中删除给定索引处的DataSet。 如果成功则返回true。
Keep in mind

After adding or removing data dynamically, notifyDataSetChanged() must be called on the chart before refreshing it (by calling invalidate()).

  • 在动态添加或删除数据之后,必须在刷新之前在图表上调用notifyDataSetChanged()(通过调用invalidate())。
 // EXAMPLE 1
 // add entries to the "data" object
 exampleData.addEntry(...);
 chart.notifyDataSetChanged(); // let the chart know it's data changed
 chart.invalidate(); // refresh

 // EXAMPLE 2
 // add entries to "dataSet" object
 dataSet.addEntry(...);
 exampleData.notifyDataChanged(); // let the data know a dataSet changed
 chart.notifyDataSetChanged(); // let the chart know it's data changed
 chart.invalidate(); // refresh

Note: Methods like moveViewTo(...) will automatically call invalidate().

  • 注意:moveViewTo(...)之类的方法会自动调用invalidate()。

15. Modifying the Viewport

This library has various methods for modifying the viewport (what is visible on the chart, aim of the view). Please note that these methods are only available for the LineChart, BarChart, ScatterChart and CandleStickChart.

  • 此库具有各种用于修改视口的方法(图表上可见的内容,视图的目标)。 请注意,这些方法仅适用于LineChart,BarChart,ScatterChart和CandleStickChart。

The methods mentioned below are provided by the Chart class. Another way to modify the viewport is to directly access it (without the in-between safety provided by the chart) via the ViewPortHandler. This is only recommended for advanced users who are familiar with the API.

  • 下面提到的方法由Chart类提供。 修改视口的另一种方法是通过ViewPortHandler直接访问它(没有图表提供的中间安全性)。 这仅适用于熟悉API的高级用户。

Please note that all methods modifying the viewport need to be called on the Chart after setting data.

  • 请注意,在设置数据后,需要在图表上调用修改视口的所有方法。

Restraining what's visible

setVisibleXRangeMaximum(float maxXRange): Sets the size of the area (range on the x-axis) that should be maximum visible at once. If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling.

  • setVisibleXRangeMaximum(float maxXRange):设置应该一次最大可见的区域大小(x轴上的范围)。如果这是例如设置为10,可以一次查看x轴上不超过10个值而无需滚动。

setVisibleXRangeMinimum(float minXRange): Sets the size of the area (range on the x-axis) that should be minimum visible at once. If this is e.g. set to 10, it is not possible to zoom in further than 10 values on the x-axis.

  • setVisibleXRangeMinimum(float minXRange):设置应该一次最小可见的区域大小(x轴上的范围)。如果这是例如如果设置为10,则无法在x轴上放大10个以上的值。

setVisibleYRangeMaximum(float maxYRange, AxisDependency axis): Sets the size of the area (range on the y-axis) that should be maximum visible at once. You also need to provide the axis this constraint should apply to.

  • setVisibleYRangeMaximum(float maxYRange,AxisDependency axis):设置应该一次最大可见的区域大小(y轴上的范围)。您还需要提供此约束应适用的轴。

setViewPortOffsets(float left, float top, float right, float bottom): Sets custom offsets for the current ViewPort (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use resetViewPortOffsets() to undo this. USE THIS ONLY WHEN YOU KNOW WHAT YOU ARE DOING.

  • setViewPortOffsets(向左浮动,向上浮动,向右浮动,浮动底部):设置当前ViewPort的自定义偏移(实际图表窗口两侧的偏移)。设置此项将阻止图表自动计算其偏移量。使用resetViewPortOffsets()来撤消此操作。只有在你知道你做什么的时候才使用它。

resetViewPortOffsets(): Resets all custom offsets set via setViewPortOffsets(...) method. Allows the chart to again calculate all offsets automatically.

  • resetViewPortOffsets():重置通过setViewPortOffsets(...)方法设置的所有自定义偏移。允许图表再次自动计算所有偏移量。

setExtraOffsets(float left, float top, float right, float bottom): Sets extra offsets (around the chart view) to be appended to the auto-calculated offsets. This does not change the auto-calculated offsets, but adds extra space to them.

  • setExtraOffsets(向左浮动,浮动顶部,向右浮动,浮动底部):设置要附加到自动计算的偏移的额外偏移(在图表视图周围)。这不会更改自动计算的偏移量,但会为它们增加额外的空间。
Moving the view (where it is aimed)

fitScreen(): Resets all zooming and dragging and makes the chart fit exactly it's bounds (fully zoom out).

  • fitScreen():重置所有缩放和拖动,使图表完全适合它的边界(完全缩小)。

moveViewToX(float xValue): Moves the left side (edge) of the current viewport to the specified x-value.

  • moveViewToX(float xValue):将当前视口的左侧(边)移动到指定的x值。

moveViewToY(float yValue, AxisDependency axis): Centers the viewport to the specified y-value on the provided y-axis (left or right).

  • moveViewToY(float yValue,AxisDependency axis):将视口居中于提供的y轴(左侧或右侧)上的指定y值。

moveViewTo(float xValue, float yValue, AxisDependency axis): This will move the left side of the current viewport to the specified x-value on the x-axis, and center the viewport to the specified y-value on the provided y-axis (makes sense in combination with setVisibleXRange(...) and setVisibleYRange(...).

  • moveViewTo(float xValue,float yValue,AxisDependency axis):这会将当前视口的左侧移动到x轴上的指定x值,并将视口居中于提供的y轴上的指定y值 (与setVisibleXRange(...)和setVisibleYRange(...)结合使用是有意义的。

centerViewTo(float xValue, float yValue, AxisDependency axis): This will move the center of the current viewport to the specified x-value and y-value (makes sense in combination with setVisibleXRange(...) and setVisibleYRange(...).

  • centerViewTo(float xValue,float yValue,AxisDependency axis):这会将当前视口的中心移动到指定的x值和y值(与setVisibleXRange(...)和setVisibleYRange(...)结合使用)。

Moving the view with animations

(since release v2.2.3)

  • moveViewToAnimated(float xValue, float yValue, AxisDependency axis, long duration): This will move the left side of the current viewport to the specified x-value on the x-axis, and center the viewport to the specified y-value on the provided y-axis in an animated way.
    • moveViewToAnimated(float xValue,float yValue,AxisDependency axis,long duration):这会将当前视口的左侧移动到x轴上的指定x值,并将视口居中放置在提供的指定y值上 y轴以动画方式。
  • centerViewToAnimated(float xValue, float yValue, AxisDependency axis, long duration): This will move the center of the current viewport to the specified x-value and y-value (according to axis) in an animated way.
    • centerViewToAnimated(float xValue,float yValue,AxisDependency axis,long duration):这将以动画方式将当前视口的中心移动到指定的x值和y值(根据轴)。

Note: All moveViewTo(...) methods will automatically invalidate() (refresh) the chart. There is no need for further calling invalidate().

  • 注意:所有moveViewTo(...)方法都将自动使图表无效()(刷新)。 无需进一步调用invalidate()。

Zooming (programmatically)

  • zoomIn(): Zooms in by 1.4f, into the charts center.

    • zoomIn():放大1.4f,进入图表中心。
  • zoomOut(): Zooms out by 0.7f, from the charts center.

    • zoomOut():从图表中心缩小0.7f。
  • zoom(float scaleX, float scaleY, float x, float y): Zooms in or out by the given scale factor. x and y are the coordinates (in pixels) of the zoom center. Remember that a scale of 1f = no zoom.

    • zoom(float scaleX,float scaleY,float x,float y):按给定的比例因子放大或缩小。 x和y是变焦中心的坐标(以像素为单位)。 请记住,1f的比例=无缩放。
  • zoom(float scaleX, float scaleY, float xValue, float yValue, AxisDependency axis): Zooms in or out by the given scale factor. xValue and yValue are the actual data values (not pixels) of the zoom center. Remember that a scale of 1f = no zoom.

    • zoom(float scaleX,float scaleY,float xValue,float yValue,AxisDependency axis):按给定的比例因子放大或缩小。 xValue和yValue是缩放中心的实际数据值(不是像素)。 请记住,1f的比例=无缩放。

Zooming with animations

(since release v2.2.3)

  • zoomAndCenterAnimated(float scaleX, float scaleY, float xValue, float yValue, AxisDependency axis, long duration): Zooms by the specified scale factor and centers the viewport to the specified values on the specified axis in an animated way.
  • zoomAndCenterAnimated(float scaleX,float scaleY,float xValue,float yValue,AxisDependency axis,long duration):缩放指定的缩放系数,并以动画方式将视口居中指定轴上的指定值。
Full example
chart.setData(...); // first set data

// now modify viewport
chart.setVisibleXRangeMaximum(20); // allow 20 values to be displayed at once on the x-axis, not more
chart.moveViewToX(10); // set the left edge of the chart to x-index 10
// moveViewToX(...) also calls invalidate()

16. Animations

Note: ANIMATIONS ONLY WORK FOR API LEVEL 11 (Android 3.0.x) AND HIGHER.

On lower Android versions, animations will not be executed (but will not crash).

  • 在较低的Android版本中,动画将不会执行(但不会崩溃)。

All chart types support animations that can be used to create / build up the chart in an awesome looking way. Three different kinds of animation methods exist that animate either both, or x- and y-axis separately:

  • 所有图表类型都支持动画,可用于以令人敬畏的方式创建/构建图表。 存在三种不同的动画方法,分别为两者或x轴和y轴设置动画:

animateX(int durationMillis): Animates the charts values on the horizontal axis, meaning that the chart will build up within the specified time from left to right.

  • animateX(int durationMillis):在水平轴上设置图表值的动画,这意味着图表将在从左到右的指定时间内建立。

animateY(int durationMillis): Animates the charts values on the vertical axis, meaning that the chart will build up within the specified time from bottom to top.

  • animateY(int durationMillis):在垂直轴上设置图表值的动画,这意味着图表将在从下到上的指定时间内构建。

animateXY(int xDuration, int yDuration): Animates both horizontal and vertical axis, resulting in a left/right bottom/top build-up.

  • animateXY(int xDuration,int yDuration):为水平和垂直轴设置动画,从而产生左/右底/顶部构建。
mChart.animateX(3000); // animate horizontal 3000 milliseconds
// or:
mChart.animateY(3000); // animate vertical 3000 milliseconds
// or:
mChart.animateXY(3000, 3000); // animate horizontal and vertical 3000 milliseconds

If animate(...) (of any kind) is called, no further calling of invalidate() is necessary to refresh the chart.

  • 如果调用animate(...)(任何类型),则不需要再次调用invalidate()来刷新图表。

Animation easing

  • 动画缓和

This library allows you to apply nice easing functions to your animations. You can choose between the following static predefined Easing.EasingOption:

  • 该库允许您将漂亮的缓动函数应用于动画。 您可以在以下静态预定义Easing.EasingOption之间进行选择:
  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,
  }

Basically, there are two ways of easing your animation:

  • 基本上,有两种方法可以简化动画:
  1. Predefined easing options: (this code will run on any Android version)
  • 预定义的缓动选项:(此代码可在任何Android版本上运行)
public void animateY(int durationmillis, Easing.EasingOption option); 

Call any animation method with a predefined easing option:

  • 使用预定义的缓动选项调用任何动画方法:
// animate both axes with easing 用缓动动画两个轴
mChart.animateY(3000, Easing.EasingOption.EaseOutBack); 

Always use Easing.EasingOption for predefined animation easing when you want your code to run below Android 3.0 (API level 11).

  • 当您希望代码在Android 3.0(API级别11)以下运行时,请始终使用Easing.EasingOption进行预定义的动画缓动。
  1. Custom easing functions: (custom easing functions will crash below Android 3.0)
  • 自定义缓动功能:(自定义缓动功能将在Android 3.0下崩溃)
public void animateY(int durationmillis, EasingFunction function); 

Create your own easing functions by creating your own easing-function class and implementing the EasingFunction interface:

  • 通过创建自己的缓动函数类并实现EasingFunction接口来创建自己的缓动函数:
/**
 * 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)
      * 动画开始后经过的时间(0到1之间的值)
     */
     public float getInterpolation(float input);
 }

Then call it this way (be aware, this will not run below Android 3.0 and crash):

  • 然后以这种方式调用它(请注意,这不会在Android 3.0下运行并崩溃):
// animate both axes with easing  用缓动动画两个轴
mChart.animateY(3000, new MyEasingFunction()); 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,312评论 0 10
  • 房间乱糟糟:地板已经三个星期没有清理了,前天舍友来我这涮锅,各种液体落在地上,现在已经变成一块块黑灰色印记;黑色的...
    知_是阅读 411评论 0 1
  • 《自私的基因》是英国生物学家理查德·道金斯所写,书中认为达尔文的“适者生存”其实是稳定者生存;宇宙是为一种稳定的物...
    江苏刘志祥阅读 164评论 0 1
  • 我想我应该是一只鬼 无人问津 孤独无依 鬼像一个遗弃在路边的破易拉罐 只有可怜的孤苦老人 伸出满是皱纹的手 拿去换...
    温琅阅读 510评论 2 6
  • 其实 不管你怎么做 不管你怎么改变 总会有人喜欢你 总会有人不喜欢你 有人喜欢我 挺好的 有人不喜欢我 也挺好的 ...
    小伊Eva阅读 121评论 0 0