Home > Blockchain >  How to add background color to every data plot (x,y value) of line chart: MPAndroidChart
How to add background color to every data plot (x,y value) of line chart: MPAndroidChart

Time:02-02

I need to set the background color of every data plot (each x/y value) of the line chart. As an example, in the figure below, the background of 82.4 value is set to orange(complete fill). Likewise, I want to add this background to every other value as well i.e. 42.1, 59.3, and 68.7 I am using the Line Chart of MPAndroidChart: implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'

Add background to each data plot

CodePudding user response:

You can use the Entry constructor that takes in a Drawable icon:

Entry(
    0f,
    0f,
    ResourcesCompat.getDrawable(
        resources,
        R.drawable.rect_blue_trans,
        context?.theme
    )
)

The icon will be drawn (unfortunately) on top of the value label, so you have to make sure that the drawable has some transparency. Also make sure that the drawable has a fixed size (in my case 16dp x 16dp):

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size android:height="16dp" android:width="16dp" />
    <solid android:color="#662E349B" />
</shape>

Then, when creating the DataSet out of the Entries make sure to enable value and icon drawing. Also you will probably have to play around with the iconsOffset to properly position the icon:

dataSet.apply {
    setDrawValues(true)
    setDrawIcons(true)
    iconsOffset = MPPointF.getInstance(0f, -8f) // try different offsets for yourself
}

This would result in chart values drawn like this (I have some of my own styling here, but it should be roughly similar):

enter image description here

  • Related