Skip to content

Line Chart

Line chart provides a UI control to present data sets represented in the form of an array of values as a line graph. You can add multiple data sets, where each set is represented by an X/Y scatter-line. The data set is assumed to be equally distributed over x values. Axis values can be customized to represent a specific value range, such as Years or Months.

Line Chart

Usage

The line chart provides a UI control with the following layout:

<com.sap.cloud.mobile.fiori.chart.LineChartView
        android:id="@+id/chart"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="60dp"
        android:background="#ccc"
        android:paddingLeft="20dp"
        android:paddingBottom="40dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Additional attributes that allow you to modify axis labels and properties:

  • Use xlabel and ylabel to specify default labels
  • Use the legendenabled flag to turn the chart legend on and off
  • Use the chartlabelfont attribute to set a different default font (the default font is f72_regular).
  • Use the legendalignment property to set the default alignment. The supported values are {"center", "left", "right"}.
<com.sap.cloud.mobile.fiori.chart.LineChartView
        android:id="@+id/chart"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="60dp"
        app:xlabel="Months"
        app:ylabel="Revenue Amount ($)"
        app:legendenabled="true"|"false"
        app:legendalignment="center"|"left"|"right"
        app:chartlabelfont="f72_regular"  />

Initializing a Line Chart

The following code initializes a LineChart.

LineChart lineChart = findViewById(R.id.chart);
//This line sets the font size
lineChart.setLegendTextSize(16.2f);

Configuring X Labels

You can specify an array of labels to be used as X-axis labels for the graph. For example, use the code below to specify each data value distributed across Months. If there are n number of data points, each data point corresponds to months[index*12/n] value.

List<String> months = Arrays.asList("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
lineChart.setXLabels(months);

Line Chart APIs

Construct line charts using one of the following three constructor methods:

  • LineChart Constructor
  • LineChart Configuration APIs
  • setYLabels(String[] labels)

LineChart Constructor

The LineChart constructor is automatically called if the control is specified with the layout. The LineChart constructor can also be called directly if you are creating the layout using direct coding. The Context type is a reference to the context of the activity in which the control is placed.

LineChart(Context context);
LineChart(Context context, AttributeSet attrs)

Line Chart Configuration APIs

Set X Axis Direction

The X axis direction can be changed to conform to different right-to-left standards. For instance, in some cases it might be useful to set the X axis orientation from right to left.

setXAxisInverted(boolean inverted)

Set the direction of the X axis. If true, the direction is right to left. If false, left to right.

lineChart.setXAxisInverted(true)

Set Axis Space

setXAxisSpaceLeft(float space)

Create extra space on the X axis to the left of the zero mark. This provides extra spacing for axisMinimum to be added to the automatically-calculated axisMinimum.

setXAxisSpaceRight(float space)

Create extra space on the X axis to the right of the maximum value. This provides extra spacing for axisMaximum to be added to the automatically-calculated axisMaximum.

Setting and Configuring X Labels

setXLabels(List<String> labels)

This sets a range of values for the X label.

List<String> months = Arrays.asList("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
lineChart.setXLabels(months);

setXlabelOverlapEnable(Boolean enable)

Long labels may sometimes overlap each other in such a way that the X-axis labels are not readable. In such cases, this API can be used to disable the overlapping by appending an ellipsis (...) to the labels. This enables or disables the xlabel overlapping as desired. By default this is disabled.

lineChart.setXlabelOverlapEnable(true)

Configuring Legend

setValueFormatter(SapLegendValueFormatter formatter)

Set formatting for the legend label values. This function is deprecated. Use setLegendValueFormatter instead (see below).

lineChart.setValueFormatter(
                       new SapLegendValueFormatter() {
                    @Override
                    public String formatXValue(float value) {
                        int labelSize = months.length;
                        int labelPos = (int) ((value - lineChart.getXChartMin()) * (labelSize-1) / lineChart.getXRange());
                        return months[labelPos];
                    }

                    @Override
                    public String formatYValue(float v) {
                        DecimalFormat format = new DecimalFormat("#,##0,000.00");
                        return format.format(v);
                    }
                    @Override
                    public String formatRangeValue(float v) {
                        DecimalFormat format = new DecimalFormat("+#,##0,000.00; -#,##0,000.00");
                        return format.format(v);
                    }

            });

setLegendValueFormatter(SapLegendValueFormatter formatter)

Set formatting for the legend label values.

lineChart.setLegendValueFormatter(
                       new SapLegendValueFormatter() {
                    @Override
                    public String formatXValue(float value) {
                        int labelSize = months.length;
                        int labelPos = (int) ((value - lineChart.getXChartMin()) * (labelSize-1) / lineChart.getXRange());
                        return months[labelPos];
                    }

                    @Override
                    public String formatYValue(float v) {
                        DecimalFormat format = new DecimalFormat("#,##0,000.00");
                        return format.format(v);
                    }
                    @Override
                    public String formatRangeValue(float v) {
                        DecimalFormat format = new DecimalFormat("+#,##0,000.00; -#,##0,000.00");
                        return format.format(v);
                    }

            });

setLegendAlignment(FioriLegendComponent.ALIGNMENT alignment)

Set the legend alignment to LEFT, RIGHT, or CENTERED.

lineChart.setLegendAlignment(FioriLegendComponent.ALIGNMENT.LEFT);
lineChart.setLegendAlignment(FioriLegendComponent.ALIGNMENT.RIGHT);
lineChart.setLegendAlignment(FioriLegendComponent.ALIGNMENT.CENTER);

Configuring Y Axis

setYAxisValueFormatter(ValueFormatter formatter)

Set formatting for the Y axis values.

lineChart.setYAxisValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                if (value == 0f) {
                    return "0";
                }
                int exp = (int) (Math.log(Math.abs(value)) / Math.log(1000));
                return String.format("%.0f%c",
                        (int) value / Math.pow(1000, exp),
                        " kMGTPE".charAt(exp));
            }

        });

setYLabels(List<String> labels)

Set a range of values for the Y label.

List<String> ylabel = Arrays.asList("Very Low", "Low", "Medium Low", "Medium High", "High", "Very High"};
lineChart.setYLabels(ylabel);

setDefaultYGridSpacingEnabled(boolean enable)

This function enables or disables the default Y axis grid spacing. By default, MPAndroidChart calculates the spacing based on the given maximum Y value and minimum Y value. At times this may cause hard-to-format values to appear on the Y axis. Disabling this will allow the user to specify a preferred specific grid spacing value.

lineChart.setDefaultYGridSpacingEnabled(enable);

setDefaultYGridSpacing(float gap)

This function sets a specific value for grid spacing. This is used in conjunction with setDefaultYGridSpacingEnabled.

lineChart.setDefaultYGridSpacing(2000);

Configuring Data for Line Chart

addDataSet(float[] values, String dataSetName)

Add a data set to the line chart.

float[] values = new float[100];
for (int i = 0; i < values.length; i++) {
    float val = (float) (Math.random() * 5) ;
    values[i] = val * 1000.0f;
}
lineChart.addDataSet(values, "2008");

updateGraph()

Redraw the UI control with all of the changes to its properties applied and with a data set.

lineChart.addDataSet(values, "2010");
lineChart.updateGraph();

resetDataSet() Reset all of the data sets.

lineChart.resetDataSet();

Configuring Chart Area

setYAxisToRight()

Set the Y axis to the right side.

lineChart.setYAxisToRight();

setYAxisToLeft()

Set the Y axis to the left side.

lineChart.setYAxisToLeft();

setDefaultYGridSpacing(float gap) Set a specific grid custom grid spacing. This will take effect only if the Default Y grid spacing is enabled.

lineChart.setDefaultYGridSpacing(2000);

setNoDataText(String text)

Sets the text that informs the user that there is no data available to display on an empty chart. If the length of the text is longer than that can fit the screen width, the text will be eclipsed (Part of the string with ending three dots ...) to fit in.

lineChart.setNoDataText("No Data Provided");

setNoDataTextColor(int color)

Sets the color of the no data text.

lineChart.setNoDataTextColor(Color.GREEN)

setNoDataTextSize(float size) Sets the text size for no data text.

lineChart.setNoDataTextSize(size);

setOnlyLimitLabels(Boolean enable)

This sets whether to display only the limit labels or all labels. If enabled, only the starting and ending X-axis labels for the visible X-axis area will be displayed. Left labels will be left-aligned and right labels will be right aligned. This is the default behavior.

lineChart.setOnlyLimitLabels(true);

setOnlyLimitLabels(boolean enable, boolean centered)

Enable or disable limit labels (the first and last labels). If centered is true then the limit labels will be centered. Otherwise left labels will be left-aligned and right labels will be right-aligned.

lineChart.setOnlyLimitLabels(true, false);

addLegendSummaryHeader(String header)

Add and set the text for the legend summary header.

lineChart.addLegendSummaryHeader("My Summary Header");

setLineChartTitle(String chartTitle)

Set the text for the chart title.

lineChart.setLineChartTitle("The Chart Title");

setStatusString(String statusString)

Set the text for the time stamp status string.

lineChart.setStatusString("Updated a minute ago")

Last update: October 2, 2020