How to set xAxis display certain value independent from entry using mpchart - android

For example, I have a data set like following:
val dataSetX = {101, 205, 210, 445, 505}
val dataSetY = {50, 100, 150, 200, 250}
The labels on the xAxis of the chart will be 101, 205, 295, 445, 505.
But I want them to be 100,200,300,400,500, without changing the data.
What do I do?

To be able to render custom labels independent from the Data Entry List you need to implement a custom XAxisRenderer and override the function fun drawLabels(c: Canvas?, pos: Float, anchor: MPPointF?) which is called when the labels are ready to be drawn on the Canvas. The default implementation uses the mXAxis.mEntryCount and mXAxis.mEntries to render the labels in the xAxis which are calculated internally by the library. What you can do is to modify the superclass implementation by overriding it without calling the super.drawLabels(c, pos, anchor) method and make the adjustments needed to handle your custom labels. Below i will describe how you can achieve this.
1.) First declare your CustomXAxisRenderer which extends from XAxisRenderer like the below example:
class CustomXAxisRenderer(viewPortHandler: ViewPortHandler?, xAxis: XAxis?, trans: Transformer?, renderXArray : Array<Float>, formatter: ValueFormatter)
: XAxisRenderer(viewPortHandler, xAxis, trans) {
private val xArray : Array<Float>
private val xValueFormatter: ValueFormatter
init {
xArray = renderXArray
xValueFormatter = formatter
}
override fun drawLabels(c: Canvas?, pos: Float, anchor: MPPointF?) {
//don't call the super class to draw the default x points
//super.drawLabels(c, pos, anchor)
val labelRotationAngleDegrees = mXAxis.labelRotationAngle
val centeringEnabled = false//mXAxis.isCenterAxisLabelsEnabled
val positions = FloatArray(xArray.size * 2)
for(i in positions.indices step 2){
// only fill x values
if (centeringEnabled) {
positions[i.toInt()] = mXAxis.mCenteredEntries[(i / 2).toInt()]
} else {
positions[i.toInt()] = xArray[(i / 2).toInt()]
}
}
mTrans.pointValuesToPixel(positions)
for(i in positions.indices step 2){
var x = positions[i]
if (mViewPortHandler.isInBoundsX(x)) {
val label = xValueFormatter.getAxisLabel(xArray[i / 2], mXAxis)
if (mXAxis.isAvoidFirstLastClippingEnabled) {
// avoid clipping of the last
if (i / 2 == xArray.size - 1 && xArray.size > 1) {
val width = Utils.calcTextWidth(mAxisLabelPaint, label).toFloat()
if (width > mViewPortHandler.offsetRight() * 2 && x + width > mViewPortHandler.chartWidth)
x -= width / 2
// avoid clipping of the first
} else if (i == 0) {
val width = Utils.calcTextWidth(mAxisLabelPaint, label).toFloat()
x += width / 2
}
}
drawLabel(c, label, x, pos, anchor, labelRotationAngleDegrees)
}
}
}
}
2.)Then you can use it like the below:
//prepare an Array of the x points to render independent of the x points in the Data Entry List
//below values must be between AxisMinimum and AxisMaximum
val renderXArray = arrayOf<Float>(0f, 150f, 250f, 350f, 400f, 433f, 505f)
//and set a custom XAxisRenderer
chart.setXAxisRenderer(CustomXAxisRenderer(chart.getViewPortHandler(), chart.getXAxis(), chart.getTransformer(YAxis.AxisDependency.LEFT), renderXArray, object : ValueFormatter() {
override fun getFormattedValue(value: Float): String {
return value.toInt().toString()
}
}))
In case you need to return a specific Label-String based on the value you can use the ValueFormatter like the below:
chart.setXAxisRenderer(CustomXAxisRenderer(chart.getViewPortHandler(), chart.getXAxis(), chart.getTransformer(YAxis.AxisDependency.LEFT), renderXArray, object : ValueFormatter() {
override fun getFormattedValue(value: Float): String {
return when (value) {
0f -> "A"
150f -> "B"
250f -> "C"
350f -> "D"
400f -> "E"
433f -> "F"
505f -> "G"
else -> ""
}
}
}))
Full Example:
chart = findViewById<LineChart>(R.id.chart)
//set xAxis properties
val xAxis = chart.xAxis
xAxis.setDrawLabels(true)
xAxis.setDrawAxisLine(true)
xAxis.setDrawGridLines(true)
xAxis.position = XAxis.XAxisPosition.BOTTOM
xAxis.axisLineWidth = 1.5f
//set xAxis Min/Max and Granularity
xAxis.setAxisMinimum(0f)
xAxis.setAxisMaximum(505f)
xAxis.setGranularity(1f)
xAxis.setGranularityEnabled(true)
//set axisLeft properties
val axisLeft = chart.axisLeft
axisLeft.setDrawLabels(true)
axisLeft.setDrawGridLines(true)
axisLeft.setDrawZeroLine(true)
axisLeft.axisLineWidth = 1.5f
axisLeft.setDrawTopYLabelEntry(true)
//set axisRight properties
val axisRight = chart.axisRight
axisRight.setDrawLabels(false)
axisRight.setDrawGridLines(false)
axisRight.setDrawZeroLine(false)
axisRight.setDrawAxisLine(false)
//prepare the Entry points
val values: ArrayList<Entry> = ArrayList()
values.add(Entry(101f, 50f))
values.add(Entry(205f, 100f))
values.add(Entry(210f, 150f))
values.add(Entry(445f, 200f))
values.add(Entry(505f, 250f))
//set the LineDataSet
val set1 = LineDataSet(values, "")
set1.setDrawCircles(true);
set1.setDrawValues(true);
//prepare LineData and set them to LineChart
val dataSets: ArrayList<ILineDataSet> = ArrayList()
dataSets.add(set1)
val data = LineData(dataSets)
chart.setData(data)
chart.getDescription().setEnabled(false);
chart.legend.isEnabled = false
//prepare an Array of the x points to render independent of the x points in the Data Entry List
//below values must be between AxisMinimum and AxisMaximum
val renderXArray = arrayOf<Float>(0f, 150f, 250f, 350f, 400f, 433f, 505f)
//and set a custom XAxisRenderer
chart.setXAxisRenderer(CustomXAxisRenderer(chart.getViewPortHandler(), chart.getXAxis(), chart.getTransformer(YAxis.AxisDependency.LEFT), renderXArray, object : ValueFormatter() {
override fun getFormattedValue(value: Float): String {
return value.toInt().toString()
}
}))
Value Result:
Label Result:
Note: This was tested with version 'com.github.PhilJay:MPAndroidChart:v3.1.0'

Related

I have a line chart that I want to use to show temperature, but I want to show icons and time in x axis

what I want to achieve
what I have
I want to show icons on the xAxis above time but line chart takes icon and places them on the value where temperature is shown. I have searched a lot but could not find the answer. Any help would be appreciated. I have tried a lot of things but all in vein.
private fun setTempChart(hour: ArrayList<Hour>, id: String) {
val entries: MutableList<Entry> = ArrayList()
for (i in hour.indices) {
val code = hour[i].condition.code
val icon =
if (hour[i].is_day == 1) requireActivity().setIconDay(code) else requireActivity().setIconNight(
code
)
entries.add(Entry(i.toFloat(), sharedPreference.temp?.let {
hour[i].temp_c.setCurrentTemperature(
it
).toFloat()
}!!))
}
val dataSet = LineDataSet(entries, "")
dataSet.apply {
lineWidth = 0f
setDrawCircles(false)
setDrawCircleHole(false)
isHighlightEnabled = false
valueTextColor = Color.WHITE
setColors(Color.WHITE)
valueTextSize = 12f
mode = LineDataSet.Mode.CUBIC_BEZIER
setDrawFilled(true)
fillColor = Color.WHITE
valueTypeface = typeface
isDrawIconsEnabled
setDrawIcons(true)
valueFormatter = object : ValueFormatter() {
override fun getFormattedValue(value: Float): String {
return String.format(Locale.getDefault(), "%.0f", value)
}
}
}
val lineData = LineData(dataSet)
chart.apply {
description.isEnabled = false
axisLeft.setDrawLabels(false)
axisRight.setDrawLabels(false)
legend.isEnabled = false
axisLeft.setDrawGridLines(false)
axisRight.setDrawGridLines(false)
axisLeft.setDrawAxisLine(false)
axisRight.setDrawAxisLine(false)
setScaleEnabled(false)
data = lineData
setVisibleXRange(8f, 8f)
animateY(1000)
xAxis.apply {
setDrawAxisLine(false)
textColor = Color.WHITE
setDrawGridLines(false)
setDrawLabels(true)
position = XAxis.XAxisPosition.BOTTOM
textSize = 12f
valueFormatter = MyAxisFormatter(hour, id)
isGranularityEnabled = true
granularity = 1f
labelCount = entries.size
}
}
}
I am using MPAndroidChart library
There isn't a nice built-in way to draw icons like that, but you can do it by making a custom extension of the LineChartRenderer and overriding drawExtras. Then you can get your icons from R.drawable.X and draw them on the canvas wherever you want. There is some work to figure out where to put them to line up with the data points, but you can copy the logic from drawCircles to find that.
Example Custom Renderer
inner class MyRenderer(private val context: Context,
private val iconY: Float,
private val iconSizeDp: Float,
chart: LineDataProvider,
animator: ChartAnimator,
viewPortHandler: ViewPortHandler)
: LineChartRenderer(chart, animator, viewPortHandler) {
private var buffer: FloatArray = listOf(0f,0f).toFloatArray()
override fun drawExtras(c: Canvas) {
super.drawExtras(c)
val iconSizePx = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
iconSizeDp,
resources.displayMetrics
)
// get the icons you want to draw
val cloudy = ContextCompat.getDrawable(context, R.drawable.cloudy)
val sunny = ContextCompat.getDrawable(context, R.drawable.sunny)
if( cloudy == null || sunny == null ) {
throw RuntimeException("Missing drawables")
}
// Determine icon width in pixels
val w = iconSizePx
val h = iconSizePx
val dataSets = mChart.lineData.dataSets
val phaseY = mAnimator.phaseY
for(dataSet in dataSets) {
mXBounds.set(mChart, dataSet)
val boundsRange = mXBounds.range + mXBounds.min
val transformer = mChart.getTransformer(dataSet.axisDependency)
for(j in mXBounds.min .. boundsRange) {
val e = dataSet.getEntryForIndex(j) ?: break
buffer[0] = e.x
buffer[1] = iconY * phaseY
transformer.pointValuesToPixel(buffer)
if( !mViewPortHandler.isInBoundsRight(buffer[0])) {
break
}
if( !mViewPortHandler.isInBoundsLeft(buffer[0]) ||
!mViewPortHandler.isInBoundsY(buffer[1])) {
continue
}
// Draw the icon centered under the data point, but at a fixed
// vertical position. Here the icon "sits on top" of the
// specified iconY value
val left = (buffer[0]-w/2).roundToInt()
val right = (buffer[0]+w/2).roundToInt()
val top = (buffer[1]-h).roundToInt()
val bottom = (buffer[1]).roundToInt()
// Alternately, use this to center the icon at the
// "iconY" value
//val top = (buffer[1]-h/2).roundToInt()
//val bottom = (buffer[1]+h/2).roundToInt()
// Use whatever logic you want to select which icon
// to use at each position
val icon = if( e.y > 68f ) {
sunny
}
else {
cloudy
}
icon.setBounds(left, top, right, bottom)
icon.draw(c)
}
}
}
}
Using the Custom Renderer
val iconY = 41f
val iconSizeDp = 40f
chart.renderer = MyRenderer(this, iconY, iconSizeDp,
chart, chart.animator, chart.viewPortHandler)
(other formatting)
val chart = findViewById<LineChart>(R.id.chart)
chart.axisRight.isEnabled = false
val yAx = chart.axisLeft
yAx.setDrawLabels(false)
yAx.setDrawGridLines(false)
yAx.setDrawAxisLine(false)
yAx.axisMinimum = 40f
yAx.axisMaximum = 80f
val xAx = chart.xAxis
xAx.setDrawLabels(false)
xAx.position = XAxis.XAxisPosition.BOTTOM
xAx.setDrawGridLines(false)
xAx.setDrawAxisLine(false)
xAx.axisMinimum = 0.5f
xAx.axisMaximum = 5.5f
xAx.granularity = 0.5f
val x = listOf(0,1,2,3,4,5,6)
val y = listOf(60,65,66,70,65,50,55)
val e = x.zip(y).map { Entry(it.first.toFloat(), it.second.toFloat())}
val line = LineDataSet(e, "temp")
line.setDrawValues(true)
line.setDrawCircles(false)
line.circleRadius = 20f // makes the text offset up
line.valueTextSize = 20f
line.color = Color.BLACK
line.lineWidth = 2f
line.setDrawFilled(true)
line.fillColor = Color.BLACK
line.fillAlpha = 50
line.mode = LineDataSet.Mode.CUBIC_BEZIER
line.valueFormatter = object : ValueFormatter() {
override fun getFormattedValue(value: Float): String {
return "%.0f F".format(value)
}
}
chart.data = LineData(line)
chart.description.isEnabled = false
chart.legend.isEnabled = false
Gives the desired effect

mpandroidchart bar chart, how to know the x value from y value?

my problem is how to know or define the other(couple) value of the y-axis or x-axis.
My code :
formatterValueY = new ValueFormatter() {
#Override
public String getAxisLabel(float valueY, AxisBase axis) {
//how to find the valueX of valueY ??
// need it to return string
//note: I know the search solution(data loop
//search),
// it is useless if there is two equal values y1=y2
//this is example of what I wanna achieve,
// this is simple example,
float x = findTheRealXOfY(valueY);
//or
//float x = findTheRealXOfY(valueY,axis);
if(x %2==0)
{
return "Pair:"+valueY;
}
else{
return "inPair:"+valueY;
}
}
}
YAxis yAxis = myBarChar.getYAxis();
yAxis.setValueFormatter(formatterValueY);
so if there is way to find the real pair value of Y using the valueY and axis.
This is an example of what I want
Depending on where you want these labels you have a couple options. If you want to set the labels along the bottom of the chart, you can use the IndexAxisValueFormatter(labels) on the x axis. If you want to add labels on the top of the bars you can set a ValueFormatter on the BarDataSet. Here is an example that sets "L" or "M" on the lower axis depending on the bar height, and "Less" or "More" on the bar label itself - also depending on the bar height.
For setting the x axis labels, the relevant command is
xaxis.valueFormatter = IndexAxisValueFormatter(labels)
and for the bar labels
barDataSet.valueFormatter = object : ValueFormatter() {
override fun getBarLabel(barEntry: BarEntry?): String {
var label = ""
barEntry?.let { e ->
// here you can access both x and y
label = if( e.y > 25 ) {
"More"
} else {
"Less"
}
}
return label
}
}
If you want the labels above the bars, you can use
barChart.setDrawValueAboveBar(true)
Complete Example
val barChart = findViewById<BarChart>(R.id.bar_chart)
// the values on your bar chart - wherever they may come from
val yVals = listOf(10f, 20f, 30f, 40f, 50f, 60f)
val valueSet1 = ArrayList<BarEntry>()
val labels = ArrayList<String>()
// You can create your data sets and labels at the same time -
// then you have access to the x and y values and can
// determine what labels to set
for (i in yVals.indices) {
val yVal = yVals[i]
val entry = BarEntry(i.toFloat(), yVal)
valueSet1.add(entry)
if( yVal > 20) {
labels.add("M")
}
else {
labels.add("L")
}
}
val dataSets: MutableList<IBarDataSet> = ArrayList()
val barDataSet = BarDataSet(valueSet1, " ")
barChart.setDrawBarShadow(false)
barChart.setDrawValueAboveBar(false)
barChart.description.isEnabled = false
barChart.setDrawGridBackground(false)
val xaxis: XAxis = barChart.xAxis
xaxis.setDrawGridLines(false)
xaxis.position = XAxis.XAxisPosition.BOTTOM
xaxis.granularity = 1f
xaxis.isGranularityEnabled = true
xaxis.setDrawLabels(true)
xaxis.setDrawAxisLine(false)
xaxis.valueFormatter = IndexAxisValueFormatter(labels)
xaxis.textSize = 15f
val yAxisLeft: YAxis = barChart.axisLeft
yAxisLeft.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
yAxisLeft.setDrawGridLines(true)
yAxisLeft.setDrawAxisLine(true)
yAxisLeft.isEnabled = true
yAxisLeft.textSize = 15f
barChart.axisRight.isEnabled = false
barChart.extraBottomOffset = 10f
barChart.extraLeftOffset = 10f
val legend: Legend = barChart.legend
legend.isEnabled = false
barDataSet.color = Color.CYAN
barDataSet.valueTextSize = 15f
// You can also set a value formatter on the bar data set itself (and enable
// setDrawValues). In this you get a BarEntry which has both the x position
// and bar height.
barDataSet.setDrawValues(true)
barDataSet.valueFormatter = object : ValueFormatter() {
override fun getBarLabel(barEntry: BarEntry?): String {
var label = ""
barEntry?.let { e ->
// here you can access both x and y
// values with e.x and e.y
label = if( e.y > 25 ) {
"More"
} else {
"Less"
}
}
return label
}
}
dataSets.add(barDataSet)
val data = BarData(dataSets)
barChart.data = data
barChart.invalidate()
example of what I needed, this is the best solution, with no over-code
this is the code:
BarData data = new BarData(colorBarSet);
data.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
Log.e("TAG", "this is the X value: " + barEntry.getX());
Log.e("TAG", "this is the Y value: " + barEntry.getY());
// this will return "Girl" for red color with x value=1,
// value of x is the index of the color in bar chart
return getMajeureVoteOfColor(barEntry.getX);
}
});

How to change line and fill color of MPAndroidChart line chart based on if y axis value is positive or negative

Was wondering if it is possible to change the line and fill color for the line chart based on if the y-axis values are positive or negative. An example of it is below
Below is what i could achieve with the following code
private fun setUpLineChart() {
val lineData = getDataSet()
view.lineChart.apply {
data = lineData
description.isEnabled = false
setScaleEnabled(false)
setTouchEnabled(false)
legend.isEnabled = false
axisLeft.apply {
setDrawLabels(false)
setDrawGridLines(false)
setDrawAxisLine(false)
spaceBottom = 30f
}
axisRight.apply {
setDrawLabels(false)
setDrawGridLines(false)
setDrawAxisLine(false)
}
xAxis.apply {
setDrawLabels(false)
setDrawGridLines(false)
setDrawAxisLine(false)
}
animateXY(700, 1000, Easing.EaseInOutQuad)
}
}
private fun getDataSet(): LineData {
val entries = mutableListOf<Entry>()
val dataList = listOf(1, 20, -20, 33, 54, 7, -18, 2)
dataList.forEachIndexed { index, element ->
entries.add(Entry(index.toFloat(), element.toFloat()))
}
val dataSet = LineDataSet(entries, "")
dataSet.apply {
setDrawCircles(false)
valueTextSize = 0f
lineWidth = 3f
mode = LineDataSet.Mode.HORIZONTAL_BEZIER
color = ContextCompat.getColor(view.context, R.color.colorOnSurface)
setDrawFilled(true)
fillColor = ContextCompat.getColor(view.context, R.color.colorSurface2)
}
return LineData(dataSet)
}
The line and fill colors are bind to a specific LineDataSet. So to achieve the result you want according to the above example you have to separate your current dataSet into 4 LineDataSets (2 positive and 2 negative) and by doing this each one then can have its own fill and line colors and you are flexible to have as many colors you want for each dataSet. Of course you have to do your own logic to separate the positive LineDataSets from negative LineDataSets. I have modified your getDataSet() function to give you an example of how to achieve the separation of positive LineDataSets from negative LineDataSets each one having its own line and fill colors.
private fun getDataSet(): LineData? {
val dataSets: MutableList<ILineDataSet> = ArrayList()
val yArray = floatArrayOf(1f, 20f, -20f, 33f, 54f, 7f, -18f, 2f)
var entries = ArrayList<Entry?>()
var prevValueIsPositive = false
var prevValueIsNegative = false
val step = 1f
for (i in yArray.indices) {
val y = yArray[i]
//positive y values
if (y >= 0) {
//we are changing to positive values so draw the current negative dataSets
if (prevValueIsNegative) {
//calculate the common mid point between a positive and negative y
val midEntry = Entry(i.toFloat() - step / 2, 0f)
entries.add(midEntry)
//draw the current negative dataSet to Red color
dataSets.add(getLineDataSet(entries, android.R.color.holo_red_dark, android.R.color.holo_purple))
//and initialize a new DataSet starting from the above mid point Entry
entries = ArrayList()
entries.add(midEntry)
prevValueIsNegative = false
}
//we are already in a positive dataSet continue adding positive y values
entries.add(Entry(i.toFloat(), y))
prevValueIsPositive = true
//not having any other positive-negative changes so add the remaining positive values in the final dataSet
if (i == yArray.size - 1) {
dataSets.add(getLineDataSet(entries, android.R.color.holo_green_light, android.R.color.holo_orange_dark))
}
} else {
//we are changing to negative values so draw the current positive dataSets
if (prevValueIsPositive) {
//calculate the common mid point between a positive and negative y
val midEntry = Entry(i.toFloat() - step / 2, 0f)
entries.add(midEntry)
//draw the current positive dataSet to Green color
dataSets.add(getLineDataSet(entries, android.R.color.holo_green_light, android.R.color.holo_orange_dark))
//and initialize a new DataSet starting from the above mid point Entry
entries = ArrayList()
entries.add(midEntry)
prevValueIsPositive = false
}
//we are already in a negative dataSet continue adding negative y values
entries.add(Entry(i.toFloat(), y))
prevValueIsNegative = true
//not having any other positive-negative changes so add the remaining negative values in the final dataSet
if (i == yArray.size - 1) {
dataSets.add(getLineDataSet(entries, android.R.color.holo_red_dark, android.R.color.holo_purple))
}
}
}
return LineData(dataSets)
}
with the usage of the below helper function to prepare a new LineDataSet with its specified line and fill colors:
private fun getLineDataSet(entries: ArrayList<Entry?>, fillColor: Int, lineColor: Int): LineDataSet {
val dataSet = LineDataSet(entries, "")
dataSet.setDrawCircles(false)
dataSet.valueTextSize = 0f
dataSet.lineWidth = 3f
dataSet.mode = LineDataSet.Mode.HORIZONTAL_BEZIER
dataSet.color = ContextCompat.getColor(this, lineColor)
dataSet.setDrawFilled(true)
dataSet.fillColor = ContextCompat.getColor(this, fillColor)
return dataSet
}

MPChart won't display hourly weather data

I'm creating a Weather app and i'm trying to display an MPChart which will use the hourly temps as Y points & the Hour (in "HH" format) as the XAxisLabels/ X points.
I'm creating the LineData for the chart in my Fragment's viewModel and expose it to the Fragment via liveData. I also create the XAxisLabels for the chart on my Fragment. The LineData seem to contain the right entries (viewModel: [Entry, x: 0.0 y: 39.07, Entry, x: 1.0 y: 38.68, Entry, x: 2.0 y: 38.16, Entry, x: 3.0 y: 37.29, Entry, x: 4.0 y: 36.2, Entry, x: 5.0 y: 35.22,........]), but the chart isn't even displaying any of the data. What am I missing here?
Here's what is rendered:
Here's the code:
ViewModel.kt
class WeatherViewModel(
private val forecastRepository: ForecastRepository,
private val weatherUnitConverter: WeatherUnitConverter,
context: Context
) : ViewModel() {
val hourlyWeatherEntries = forecastRepository.getHourlyWeather()
val hourlyChartData = hourlyWeatherEntries.switchMap { hourlyData ->
liveData {
Log.d("ViewModel hourly data", "$hourlyData")
val task = viewModelScope.async(Dispatchers.Default) {
createChartData(hourlyData)
}
emit(task.await())
}
}
/**
* Creates the line chart's data and returns them.
* #return The line chart's data (x,y) value pairs
*/
private fun createChartData(hourlyWeather: List<HourWeatherEntry>?): LineData {
if (hourlyWeather == null) return LineData()
Log.d("ViewModel class", hourlyWeather.toString())
val unitSystemValue = preferences.getString(UNIT_SYSTEM_KEY, "si")!!
val values = arrayListOf<Entry>()
for (i in hourlyWeather.indices) { // init data points
// format the temperature appropriately based on the unit system selected
val hourTempFormatted = when (unitSystemValue) {
UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> hourlyWeather[i].temperature
UnitSystem.US.name.toLowerCase(Locale.ROOT) -> weatherUnitConverter.convertToFahrenheit(
hourlyWeather[i].temperature
)
else -> hourlyWeather[i].temperature
}
// Create the data point
values.add(
Entry(
i.toFloat(),
hourTempFormatted.toFloat(),
appContext.resources.getDrawable(
determineSummaryIcon(hourlyWeather[i].icon),
null
)
)
)
}
Log.d("MainFragment viewModel", "$values")
// create a data set and customize it
val lineDataSet = LineDataSet(values, "")
val color = appContext.resources.getColor(R.color.black, null)
val offset = MPPointF.getInstance()
offset.y = -35f
lineDataSet.apply {
valueFormatter = YValueFormatter()
setDrawValues(true)
fillDrawable = appContext.resources.getDrawable(R.drawable.gradient_night_chart, null)
setDrawFilled(true)
setDrawIcons(true)
setCircleColor(color)
mode = LineDataSet.Mode.HORIZONTAL_BEZIER
this.color = color // line color
iconsOffset = offset
lineWidth = 3f
valueTextSize = 9f
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
valueTypeface = appContext.resources.getFont(R.font.work_sans_medium)
}
}
// create a LineData object using our LineDataSet
val data = LineData(lineDataSet)
data.apply {
setValueTextColor(R.color.colorPrimary)
setValueTextSize(15f)
}
return data
}
}
MainFragment.kt
class MainFragment : Fragment() {
// Lazy inject the view model
private val viewModel: WeatherViewModel by viewModel()
private lateinit var hourlyChart: LineChart
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpChart()
lifecycleScope.launch {
// Shows a lottie animation while the data is being loaded
//scrollView.visibility = View.GONE
//lottieAnimView.visibility = View.VISIBLE
bindUIAsync().await()
// Stops the animation and reveals the layout with the data loaded
//scrollView.visibility = View.VISIBLE
//lottieAnimView.visibility = View.GONE
}
}
#SuppressLint("SimpleDateFormat")
private fun bindUIAsync() = lifecycleScope.async(Dispatchers.Main) {
// fetch hourly chart line data
val hourlyChartData = viewModel.hourlyChartData
hourlyChartData.observe(viewLifecycleOwner, Observer { lineData ->
if(lineData == null) {
Log.d("HOURLY CHART DATA", "Line data = null")
return#Observer
}
hourlyChart.data = lineData
hourlyChart.invalidate()
})
// fetch hourly weather
val hourlyWeather = viewModel.hourlyWeatherEntries//viewModel.hourlyWeatherEntries
// Observe the hourly weather live data
hourlyWeather.observe(viewLifecycleOwner, Observer { hourly ->
if (hourly == null) return#Observer
val xAxisLabels = arrayListOf<String>()
val sdf = SimpleDateFormat("HH")
for (i in hourly.indices) {
val formattedLabel = sdf.format(Date(hourly[i].time * 1000))
xAxisLabels.add(formattedLabel)
}
setChartAxisLabels(xAxisLabels)
Log.d(TAG, "label count = ${hourlyChart.xAxis.labelCount.toString()}")
})
return#async true
}
private fun setChartAxisLabels(labels: ArrayList<String>) {
// Populate the X axis with the hour labels
hourlyChart.xAxis.valueFormatter = IndexAxisValueFormatter(labels)
}
/**
* Sets up the chart with the appropriate
* customizations.
*/
private fun setUpChart() {
hourlyChart.apply {
description.isEnabled = false
setNoDataText("Data is loading...")
// enable touch gestures
setTouchEnabled(true)
dragDecelerationFrictionCoef = 0.9f
// enable dragging
isDragEnabled = true
isHighlightPerDragEnabled = true
setDrawGridBackground(false)
axisRight.setDrawLabels(false)
axisLeft.setDrawLabels(false)
axisLeft.setDrawGridLines(false)
// disable zoom functionality
setScaleEnabled(false)
setPinchZoom(false)
isDoubleTapToZoomEnabled = false
// disable the chart's legend
legend.isEnabled = false
// append extra offsets to the chart's auto-calculated ones
setExtraOffsets(0f, 0f, 0f, 10f)
data = LineData()
data.isHighlightEnabled = false
setVisibleXRangeMaximum(6f)
setBackgroundColor(resources.getColor(R.color.bright_White, null))
}
// X Axis setup
hourlyChart.xAxis.apply {
position = XAxis.XAxisPosition.BOTTOM
textSize = 14f
setDrawLabels(true)
setDrawAxisLine(false)
setDrawGridLines(false)
isEnabled = true
granularity = 1f // one hour
spaceMax = 0.2f // add padding start
spaceMin = 0.2f // add padding end
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
typeface = resources.getFont(R.font.work_sans)
}
textColor = resources.getColor(R.color.black, null)
}
// Left Y axis setup
hourlyChart.axisLeft.apply {
setDrawLabels(true)
setDrawGridLines(false)
setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
// temperature values range (higher than probable temps in order to scale down the chart)
axisMinimum = 0f
axisMaximum = when (getUnitSystemValue()) {
UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> 50f
UnitSystem.US.name.toLowerCase(Locale.ROOT) -> 150f
else -> 50f
}
}
// Right Y axis setup
hourlyChart.axisRight.apply {
setDrawGridLines(false)
isEnabled = false
}
}
}

Custom label indicators on xAxis in MpAndroidChart

I am using a chart library called MPAndroidChart and it responds to most of my needs. However, I need to customize some parts.
I want to draw some indicator lines for labels on xAxis like this :
As I dug in, I could write a CustomAxisRenderer but it seems I need to copy most of the super class codes.
I want the min value to be drawn exactly on xAxis. This min value could be 0 or any other number as well.
How can this be done? Is it even possible to do it?
Any help or hint would be appreciated.
I solved the first issue:
internal class IndicatorAxisRenderer(
viewPortHandler: ViewPortHandler,
xAxis: XAxis,
trans: Transformer
) : XAxisRenderer(viewPortHandler, xAxis, trans) {
private var indicatorWidth = 1f
private var indicatorHeight = 1f
private fun getXLabelPositions(): FloatArray {
var i = 0
val positions = FloatArray(mXAxis.mEntryCount * 2)
val centeringEnabled = mXAxis.isCenterAxisLabelsEnabled
while (i < positions.size) {
if (centeringEnabled) {
positions[i] = mXAxis.mCenteredEntries[i / 2]
} else {
positions[i] = mXAxis.mEntries[i / 2]
}
positions[i + 1] = 0f
i += 2
}
mTrans.pointValuesToPixel(positions)
return positions
}
override fun renderAxisLine(c: Canvas?) {
super.renderAxisLine(c)
val positions = getXLabelPositions()
var i = 0
while (i < positions.size) {
val x = positions[i]
if (mViewPortHandler.isInBoundsX(x)) {
val y = mViewPortHandler.contentBottom()
c?.drawLine(
x, y,
x, y + indicatorHeight,
mAxisLinePaint
)
}
i += 2
}
}
fun setIndicatorSize(width: Float, height: Float) {
this.indicatorWidth = width
this.indicatorHeight = height
}
}
This code renders indicator lines on top of the xAxis.

Categories

Resources