Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert x value labels to String? from Double? [Horizontal Barchart] (Swift v3) #1527

Closed
sree127 opened this issue Sep 22, 2016 · 14 comments
Closed

Comments

@sree127
Copy link

sree127 commented Sep 22, 2016

I'm not able to figure out how to convert the x value labels to String?

screen shot 2016-09-22 at 9 43 31 am

Is it possible to convert the values to ["Jan", "Feb", "Mar"] instead of [1, 2, 3].. ?

@Huang-Libo
Copy link

Huang-Libo commented Sep 22, 2016

@sree127 You can use NSTimeInterval to store date, then use a formatter to custom it.
Also you can search NSTimeInterval at issue, you will get more info about this.

@sree127
Copy link
Author

sree127 commented Sep 22, 2016

Hi @Huang-Libo. Thanks for replying. Can xaxis values take any String values? There are no examples in demo on how to use IAxisValueFormatter . Can you please help me with that? The data I'd be displaying will be dynamic strings. Thanks a lot

@Huang-Libo
Copy link

Huang-Libo commented Sep 22, 2016

@sree127

  1. xAxis can only store double value, as Daniel @danielgindi said before, with a formatter, a double value can present any type of thing .
  2. You can look at "Time Line Chart" In Demo:-)

@sree127
Copy link
Author

sree127 commented Sep 22, 2016

Thanks a lot @Huang-Libo. That was easier than I'd thought :-)

@sree127 sree127 closed this as completed Sep 22, 2016
@jayvenn
Copy link

jayvenn commented Sep 25, 2016

This is what I spent a lot of time trying to figure out. I used a website to convert obj-c code to swift. Still can't get any of it to work properly. All I want is A, B, C, D on the xAxis. Thanks in advance to helpers.

`import UIKit
import Charts

class ViewController: UIViewController, ChartViewDelegate {

@IBOutlet weak var barChartView: BarChartView!

var dataEntries: [BarChartDataEntry] = []

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    barChartView.delegate = self
    barChartView.drawGridBackgroundEnabled = false
    barChartView.legend.enabled = false
    barChartView.isUserInteractionEnabled = false
    barChartView.rightAxis.enabled = false
    barChartView.drawValueAboveBarEnabled = true

    let xAxis = barChartView.xAxis
    xAxis.drawGridLinesEnabled = false
    xAxis.valueFormatter = DateValueFormatter()

    let yAxis = barChartView.leftAxis
    yAxis.drawGridLinesEnabled = false


    var yValues: [Double] = [2, 3, 1, 3, 4]
    var xValues: [String] = ["A", "B", "C", "D"]

    self.setDataCount(count: 4, range: 30.0)
}

func setDataCount(count: Int, range: Double) {
    var now = Date().timeIntervalSince1970
    var hourSeconds = 3600.0
    var values = [ChartDataEntry]()
    var from = now - (Double(count) / 2.0) * hourSeconds
    var to = now + (Double(count) / 2.0) * hourSeconds

    var x = from
    while x < to {
        var y: Double = Double(arc4random_uniform(UInt32(range)))
        values.append(ChartDataEntry(x: x, y: y))
        x += hourSeconds
    }
    var set1: BarChartDataSet? = nil

    if (barChartView.data?.dataSetCount)! > 0 {
        set1 = (barChartView.data?.dataSets[0] as! BarChartDataSet)
        set1!.values = values as! [ChartDataEntry]

        barChartView.notifyDataSetChanged()
    } else {
        set1 = BarChartDataSet(values: values, label: "data set 1")

        set1!.valueTextColor = UIColor(red: 51 / 255.0, green: 181 / 255.0, blue: 229 / 255.0, alpha: 1.0)
        set1!.drawValuesEnabled = false
        set1!.highlightColor = UIColor(red: 224 / 255.0, green: 117 / 255.0, blue: 117 / 255.0, alpha: 1.0)
        var dataSets = [IChartDataSet]()
        dataSets.append(set1!)

        var data = BarChartData(dataSets: dataSets)
        self.barChartView.data = data
    }
}

}`

@sree127
Copy link
Author

sree127 commented Sep 25, 2016

Hey @nhantrivinh, you're setting the xAxis.valueFormatter wrong. You can use the IAxisValueFormatter to change the values. Here is what I've used 👍

class ChartStringFormatter: NSObject, IAxisValueFormatter {

    var nameValues: [String]! =  ["A", "B", "C", "D"]

    public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        return String(describing: nameValues[Int(value)])
    }
}

And while setting the data :

let formatter = ChartStringFormatter()
 xAxis.valueFormatter = formatter

@tuantmdev
Copy link

@nhantrivinh use the code that @sree127 provided above and dont forget to set granularity = 1

@jorgemauricio
Copy link

@tuantmdev What if I generate the string on the go, or outside the class?

@tuantmdev
Copy link

tuantmdev commented Sep 30, 2016

@jorgemauricio Pass the name values as a property of the Formatter

var formatter = ChartStringFormatter()
formatter.nameValues = ["A", "B", "C", "D"] //anything you want
xAxis.valueFormatter = formatter
xAxis.granularity = 1

Just remember set formatter before set chartView.data = data of chartView

@Carielle
Copy link

Carielle commented Oct 3, 2016

Can anyone help me? I tried to follow the ChartsDemo example and the suggestions here, but my horizontal bar chart is still coming out wrong. I'll include my code, basically I'm trying to label each bar with a bit of text, but I'm getting labels on the gridlines instead of one label for each bar.

To set up the chart...

` double barWidth = 6.0;
double spaceForBar = 7.0;

dataList = dataPoints;

barChartView.noDataText = @"You need to provide data for the chart.";

[barChartView animateWithYAxisDuration:1.0];

barChartView.doubleTapToZoomEnabled = NO;
barChartView.pinchZoomEnabled = NO;
barChartView.scaleXEnabled = NO;
barChartView.scaleYEnabled = NO;

barChartView.descriptionText = @"";
//barChartView.descriptionText = unit;
NSLog(@"%@", unit);

ChartXAxis *xAxis = barChartView.xAxis;
xAxis.granularity = 1.0;
xAxis.valueFormatter = self;

barChartView.xAxis.labelPosition = XAxisLabelPositionBottom;

barChartView.leftAxis.labelCount = 4;
barChartView.leftAxis.axisMinValue = 0;

barChartView.rightAxis.labelCount = 4;
barChartView.rightAxis.axisMinValue = 0;

barChartView.extraBottomOffset = 30.0;
barChartView.legend.enabled = false;
barChartView.fitBars = YES;

NSMutableArray *dataEntries =[[NSMutableArray alloc] init];

for (int i = 0; i < count; i++)
{
    NSNumber *value = [values objectAtIndex:i];
    NSString *car_model = [dataPoints objectAtIndex:i];
    NSLog(@"%@",car_model);
    // Need to put car model in as x "value"
    BarChartDataEntry *dataEntry = [[BarChartDataEntry alloc] initWithX:i*spaceForBar y:[value doubleValue]];
    [dataEntries addObject:dataEntry];
    NSLog(@"%d", i);
}

BarChartDataSet *chartDataSet = [[BarChartDataSet alloc] initWithValues:dataEntries];
NSMutableArray *colorSet = [self getColorSet:chartDataSet :isGreenHigh];

chartDataSet.colors = colorSet;

NSMutableArray *dataSets = [[NSMutableArray alloc] init];
[dataSets addObject:chartDataSet];
BarChartData *chartData = [[BarChartData alloc] initWithDataSets:dataSets];
chartData.barWidth = barWidth;

//BarChartData *chartData = [[BarChartData alloc] initWithXVals:dataPoints dataSets:dataSets];
barChartView.data = chartData;
barChartView.data.highlightEnabled = NO;

`

My stringForValue function where dataList is my NSArray of label strings...

`- (NSString *)stringForValue:(double)value
axis:(ChartAxisBase *)axis
{
NSString *string;
string = dataList[(int)value % dataList.count];
return string;

}`

And this is what my chart looks like...
snip20161003_3

@tuantmdev
Copy link

@Carielle
The value of x you pass when init BarChartDataEntry should be the same the value of formatter method

- (NSString *)stringForValue:(double)value axis:(ChartAxisBase *)axis

In your case, i think it should change to

BarChartDataEntry *dataEntry = [[BarChartDataEntry alloc] initWithX:i y:[value doubleValue]];

@goel232
Copy link

goel232 commented Feb 3, 2017

@venkatesh613
Copy link

hi everyone
how to change bar values to int values
in bar chart showing 61.5 like this
In above bar chart
please help me

@ClarissaW
Copy link

@sree127
Hi, can you tell me how you can position your value labels inside of bars? Is there a property that can achieve that? BTW, thanks for asking the question you mentioned here. I met the same issue but got fixed here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants