ductran
ductran

Reputation: 10193

MPAndroidChart set center vertical line

I want to set a vertical line in center of LineChart like this:

enter image description here

When scrolling to each point, it can notify to change the date below (the orange date field). And it can move left or right programmatically by click on arrow button.

Currently, I can set viewport and allow moving to center with this code:

LineData data = new LineData(xVals, dataSets);
mChart.setScaleMinima((float) data.getXValCount() / 7f, 1f);
mChart.moveViewTo(0, 7, YAxis.AxisDependency.LEFT);

And get the result:

enter image description here

How can I draw and set a vertical line like above?

Update:

For the listener, I think OnChartGestureListener onChartTranslate(MotionEvent me, float dX, float dY) may help. What I need is the distance between 2 points and how to calculate how many points are in current view port. Does anyone know that?

Upvotes: 12

Views: 5115

Answers (3)

Daniel Coello
Daniel Coello

Reputation: 41

Maybe it's too late but here is my answer. It's encoded in Swift using Charts (MPAndroidCharts port for iOS) but API is 99% the same ;)

let verticalPointEntry = ChartDataEntry(x: xValue, y: yValue)

let dataSet = LineChartDataSet(values: [verticalPointEntry], label: "")
dataSet.drawCirclesEnabled = false
dataSet.drawValuesEnabled = false
dataSet.setDrawHighlightIndicators(true)
dataSet.drawHorizontalHighlightIndicatorEnabled = false
dataSet.highlightColor = UIColor.white
dataSet.highlightLineWidth = 1   

let highlightPoint = Highlight(x: xValue, y: yValue, dataSetIndex: datasetIndex)
self.highlightValues([highlightPoint])

// "yourNormalDataSet" is your regular dataSet in which you want to display vertical line over it
let chartData = LineChartData(dataSets: [yourNormalDataSet, dataSet])
self.data = chartData
self.data?.notifiyDataChanged()
self.notifyDataSetChanged

This will display a vercital line over the point defined by your xValue variable.

Hope it helps!

Upvotes: 3

Cory Charlton
Cory Charlton

Reputation: 8938

Have you tried using getEntryByTouchPoint on your chart supplying the x and y coordinates of the center of the chart?

public Entry getEntryByTouchPoint(float x, float y)

returns the Entry object displayed at the touched position of the chart

Upvotes: 6

Lanitka
Lanitka

Reputation: 932

Take a look at the method

protected void drawGridBackground(Canvas c) {

in the BarLineChartBase class (parent for a LineChart). In that method you have all data to draw your line right in the middle. Something like this

RectF rectF = mViewPortHandler.getContentRect();
float xMiddle = (rectF.right - rectF.left)/2;
Paint p = new Paint();
p.setColor(Color.BLACK);
c.drawLine(xMiddle, rectF.bottom, xMiddle, rectF.top, p);

Upvotes: 5

Related Questions