Vinay Podili
Vinay Podili

Reputation: 345

Swift ios : Implement scroll on Bar chart

Tried to implement scroll on Barchart using scale x to 2 for zoom in. But the issue is the x-axis values are not center-aligned with Bar chart. Labels count is based on day and month values.

barChartView.xAxis.axisMinimum = 0.0
barChartView.xAxis.axisMaximum = Double(labels.count - 1)

barChartView.setVisibleXRangeMaximum(Double(labels.count)/2)
or 
barChartView.zoom(scaleX: 2, scaleY: 0, x: 0, y: 0)

for scroll implemented like,

barChartView.xAxis.setLabelCount(Int(Double(labels.count)/2), force: true)

Please suggest to us the correct approach to avoid miss align of x-axis values with the bar chart.

enter image description here

enter image description here

Upvotes: 4

Views: 2103

Answers (2)

anas.p
anas.p

Reputation: 2286

To make the chart horizontal scroll and adjust the bars and y-axis labels properly:

let visibleXRange = 6 // Number of values to show in y-Axis
barChartView.xAxis.axisMaximum = Double(xAxisValues.count)
barChartView.setVisibleXRangeMaximum(Double(visibleXRange))
barChartView.xAxis.setLabelCount(visibleXRange, force: false)
barChartView.xAxis.granularity = 1
barChartView.xAxis.labelCount = visibleXRange

Make sure the dragEnabled = true

Upvotes: 0

miwin
miwin

Reputation: 1215

From your code, I assume your expected behaviour is that the chart

  • shows at most half of all available bars
  • allows the user to zoom indefinitly (minimum = 0)
  • allows the user to scroll (left/right)

If this is the case, you would apply the following code:

barChartView.xAxis.axisMinimum = 0.0
barChartView.xAxis.axisMaximum = Double(labels.count - 1)

barChartView.setVisibleXRangeMaximum(Double(labels.count)/2)
barChartView.xAxis.setLabelCount(Int(Double(labels.count)/2), force: false)

.zoomshould be avoided since it sets multiple unwanted values (scaleY, x, y) and hence adds unwanted features when scrolling.

It is important to set the force flag to false. This is the parameter that caused your miss alignment as described in the documentation:

https://weeklycoding.com/mpandroidchart-documentation/axis-general/

setLabelCount(int count, boolean force): Sets the number of labels for the y-axis. Be aware that this number is not fixed (if force == false) and can only be approximated. If force is enabled (true), then the exact specified label-count is drawn – this can lead to uneven numbers on the axis.

Upvotes: 2

Related Questions