Вопрос

I have looked over a lot of sample tutorials of Core plot but having issues in most of them. If Can anyone provide a working tutorial for creating line graph with data X=(Sep,Oct,Nov,Dec) and Y=(20,40,80,30) with X & Y axes also using Core Plot framework in iOS? Any code would be much helpful to me..

Это было полезно?

Решение

If you want to make a linear graph in core plot, there are some things to keep in mind. First make sure that you make your view controller able to graph things. You need to make it the plot delegate, plot data source and the plotspace delegate.

@interface ViewController : UIViewController <CPTScatterPlotDelegate, CPTPlotSpaceDelegate, CPTPlotDataSource>

This is added in the .h file. **Don't forget to import the CorePlot-cocoaTouch.h too!

Next, in the view did appear method you would want to place your variables into an array. Here is a sample that I did to make a quick linear graph.

- (void)viewDidAppear:(BOOL)animated
{
float b = 1;
float c = 5;

Xmax = 10;
Xmin = -10;
Ymax = 10;
Ymin = -10;

float inc = (Xmax - Xmin) / 100.0f;
float l = Xmin;

NSMutableArray *linearstuff = [NSMutableArray array];

for (int i = 0; i < 100; i ++)
{
    float y = (b * (l)) + c;
    [linearstuff addObject:[NSValue valueWithCGPoint:CGPointMake(l, y)]];
    NSLog(@"X and Y = %.2f, %.2f", l, y);
    l = l + inc;
}

self.data = linearstuff;
[self initPlot];
}

The call to [self initPlot] calls a function to actually make the graphs. It is very similar to all the sample code that is out there.

Once you have your data into an array, the next things is to make the graphs the way you want them to look. Once again take a look at all the code for configureHost, configure Graph, and stuff like that, it is right on the Core Plot website. Another important thing to remember is the numberOfRecordsForPlot method. Here is sample of mine. This lets you know how many data points you have.

- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return [_data count];
}

_data is the array I made to store everything. Next you want to graph the data. With numberForPlot method. Once again here is a sample.

- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSLog(@"numberForPlot");
if ([plot.identifier isEqual:@"linear"])
{
    NSValue *value = [self.data objectAtIndex:index];
    CGPoint point = [value CGPointValue];

    // FieldEnum determines if we return an X or Y value.
    if (fieldEnum == CPTScatterPlotFieldX) 
    {
        return [NSNumber numberWithFloat:point.x];

    }
    else    // Y-Axis
    {
        return [NSNumber numberWithFloat:point.y];

    }
    NSLog(@"x is %.2f", point.x);
    NSLog(@"y is %.2f", point.y);
}
return [NSNumber numberWithFloat:0];
}

Hopefully this will get you started. Core Plot is an excellent way to graph things and their website is full of great information. Hope this helps.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top