在iOS中从JSON动态加载Scatter(Line)图表?

时间:2015-03-09 07:57:50

标签: xcode uipickerview core-plot scatter-plot

我是corePlot的新手,当我们在UIPickerView中选择一个特定的行时,我无法从json动态绘制图形(Line)。  在这里,

Line graph with x-axis: Time as 02,03,04,.....
                       y-axis: temperature as 10,20,30,.....



UIPickerView consists of Date(s). for eg: we have 3 rows :
        06-03-2015, 07-03-2015, 08-03-2015

现在如果我们在U​​IPickerView中选择任何特定的行,我必须显示折线图。我已经完成了静态数据,但现在我遇到了动态数据的问题。

    -(void)initialisePlot
{
    // Start with some simple sanity checks before we kick off
    if ( (self.hostingView == nil) || (self.graphData == nil) ) {
        NSLog(@"TUTSimpleScatterPlot: Cannot initialise plot without hosting view or data.");
        return;
    }

    if ( self.graph != nil ) {
        NSLog(@"TUTSimpleScatterPlot: Graph object already exists.");
        return;
    }

    // Create a graph object which we will use to host just one scatter plot.
    CGRect frame = [self.hostingView bounds];


    //CGRect frame = [self.hostingView bounds];

     //CGRect frame = [self.hostingView frame];
    self.graph = [[CPTXYGraph alloc] initWithFrame:frame] ;


    //self.hostingView=[[CPTGraphHostingView alloc]initWithFrame:CGRectMake(0.0, 0.0, 900.0, 420.0)];
    //self.graph = [[CPTXYGraph alloc] initWithFrame:self.hostingView.bounds];

    // Add some padding to the graph, with more at the bottom for axis labels.
    self.graph.plotAreaFrame.paddingTop = 20.0f;
    self.graph.plotAreaFrame.paddingRight = 10.0f;
    self.graph.plotAreaFrame.paddingBottom = 50.0f;
    self.graph.plotAreaFrame.paddingLeft = 60.0f;

    // Tie the graph we've created with the hosting view.
    self.hostingView.hostedGraph = self.graph;

    // If you want to use one of the default themes - apply that here.
    [self.graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];

    // Create a line style that we will apply to the axis and data line.
    CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
    lineStyle.lineColor = [CPTColor whiteColor];
    lineStyle.lineWidth = 2.0f;

    // Create a text style that we will use for the axis labels.
    CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
    textStyle.fontName = @"Helvetica";
    textStyle.fontSize = 14;
    textStyle.color = [CPTColor whiteColor];

    // Create the plot symbol we're going to use.
    CPTPlotSymbol *plotSymbol = [CPTPlotSymbol crossPlotSymbol];
    plotSymbol.lineStyle = lineStyle;
    plotSymbol.size = CGSizeMake(8.0, 8.0);     

    // Setup some floats that represent the min/max values on our axis.
    int xAxisMin = 0;
    int xAxisMax = 20;
    float yAxisMin = 0;
    float yAxisMax = 50;


    // We modify the graph's plot space to setup the axis' min / max values.
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(xAxisMin) length:CPTDecimalFromInt(xAxisMax-xAxisMin)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(yAxisMin) length:CPTDecimalFromFloat(yAxisMax - yAxisMin)];

    // Modify the graph's axis with a label, line style, etc.
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;

    axisSet.xAxis.title = @"Time";
    axisSet.xAxis.titleTextStyle = textStyle;
    axisSet.xAxis.titleOffset = 20;
    axisSet.xAxis.axisLineStyle = lineStyle;
    axisSet.xAxis.majorTickLineStyle = lineStyle;
    axisSet.xAxis.minorTickLineStyle = lineStyle;
    axisSet.xAxis.labelTextStyle = textStyle;
    axisSet.xAxis.labelOffset = 3;
    axisSet.xAxis.majorIntervalLength = CPTDecimalFromInt(2);
    axisSet.xAxis.minorTicksPerInterval = 1;
    axisSet.xAxis.minorTickLength = 5;
    axisSet.xAxis.majorTickLength = 7;


    axisSet.yAxis.title = @"Temperature";
    axisSet.yAxis.titleTextStyle = textStyle;   
    axisSet.yAxis.titleOffset = 40.0f;  
    axisSet.yAxis.axisLineStyle = lineStyle;    
    axisSet.yAxis.majorTickLineStyle = lineStyle;
    axisSet.yAxis.minorTickLineStyle = lineStyle;
    axisSet.yAxis.labelTextStyle = textStyle;   
    axisSet.yAxis.labelOffset = 3.0f;   
    axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(10.0f);
    axisSet.yAxis.minorTicksPerInterval = 1;
    axisSet.yAxis.minorTickLength = 5.0f;
    axisSet.yAxis.majorTickLength = 7.0f;   

    // Add a plot to our graph and axis. We give it an identifier so that we 
    // could add multiple plots (data lines) to the same graph if necessary.
    CPTScatterPlot *plot = [[CPTScatterPlot alloc] init] ;
    plot.dataSource = self;
    plot.identifier = @"mainplot";
    plot.dataLineStyle = lineStyle;
    plot.plotSymbol = plotSymbol;
    [self.graph addPlot:plot];  
}

// Delegate method that returns the number of points on the plot
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot 
{
    if ( [plot.identifier isEqual:@"mainplot"] ) 
    {
        return [self.graphData count];
    } 

    return 0;
}

// Delegate method that returns a single X or Y value for a given plot.
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    if ( [plot.identifier isEqual:@"mainplot"] ) 
    {

        NSValue *value = [self.graphData objectAtIndex:index];
        CGPoint point = [value CGPointValue];

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

    return [NSNumber numberWithFloat:0];
}

在viewDidLoad中,我按如下方式调用此方法:

pickerData = [[NSArray alloc] initWithObjects:@" 28-02-2015",@" 01-03-2015",@" 02-03-2015& #34;,@" 03-03-2015",@" 04-03-2015",nil];      NSMutableArray * data1 = [NSMutableArray array];             [data1 addObject:[NSValue valueWithCGPoint:CGPointMake(0,0)]];

    self.scatterPlot = [[TUTSimpleScatterPlot alloc] initWithHostingView:_graphHostingView andData:data1];
    [self.scatterPlot initialisePlot];
使用动态数据

pickerView数据源和委托方法如下:

      #pragma mark PickerView DataSource

        - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
        {
            return 1;
        }

        - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
        {
            return pickerData.count;
        }

        - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
        {
            return pickerData[row];
        }

        #pragma mark -
        #pragma mark PickerView Delegate
        -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

    //PickerModal *pModal=[picDataArray objectAtIndex:row];

    pickObj=[picDataArray objectAtIndex:row];
    //result=[NSString stringWithFormat:@"%@",pickObj.picDate];

    NSLog(@"time :%@",pickObj.picTime);
    NSLog(@"temp :%@",pickObj.picTemperature);


    for (int i=0; i<50; i++) {
        int selectedRow=[self.myPickerView selectedRowInComponent:0];
        if ((selectedRow=i)) {
            NSMutableArray *data1 = [NSMutableArray array];

            [data1 addObject:[NSValue valueWithCGPoint:CGPointMake([pickObj.picTime floatValue], [pickObj.picTemperature floatValue])]];
            NSMutableArray *arr=[[NSMutableArray alloc]initWithArray:data1];

            self.scatterPlot = [[TUTSimpleScatterPlot alloc] initWithHostingView:_graphHostingView andData:arr];
            [self.scatterPlot initialisePlot];

        }

    }

    [pickerView reloadComponent:0];
}

我将json数据解析为:

-(void)retrieveData{

    NSString *sensorTagID=@"UIUIA6767672345678910987654321";

    NSMutableString *globalUrlString=[NSMutableString stringWithString:@"url"];
    [globalUrlString appendString:[NSString stringWithFormat:@"?SensorTagID=%@",sensorTagID]];


    NSLog(@"url string:%@",globalUrlString);

    NSURL *url=[NSURL URLWithString:globalUrlString];

    NSMutableURLRequest *globalRequest=[NSMutableURLRequest requestWithURL:[url standardizedURL]];

    [globalRequest setHTTPMethod:@"GET"];

    NSError *error = nil;
    NSURLResponse *theResponse = [[NSURLResponse alloc]init];

    //connecting to the server
    NSData *data = [NSURLConnection sendSynchronousRequest:globalRequest returningResponse:&theResponse error:&error];

    //NSData *data=[NSData dataWithContentsOfURL:url];

    json=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    picDataArray=[[NSMutableArray alloc]init];

    for (int i=0; i<json.count; i++) {

       pickDate=[[json objectAtIndex:i]valueForKey:@"Date"];
        NSLog(@"date %@",pickDate);

        NSArray *getEvents=[[json objectAtIndex:i]valueForKey:@"OnDateSensorValues"];
        for (NSDictionary *eventsObj in getEvents) {
            pickHumidity=eventsObj[@"Humidity"];
            //NSLog(@"humidity %@",pickHumidity);

            pickLocationHumidity=eventsObj[@"LocationHumidity"];
            //NSLog(@"locHumidity %@",pickLocationHumidity);

            pickLocationTemperature=eventsObj[@"LocationTemperature"];
            //NSLog(@"locTemp %@",pickLocationTemperature);

            pickTemperature=eventsObj[@"Temperature"];
            NSLog(@"temp %@",pickTemperature);

            pickTime=eventsObj[@"Time"];
            NSLog(@"time %@",pickTime);


               }

            pickObj=[[PickerModal alloc]initWithPicDate:pickDate andPicHumidity:pickHumidity andPicLocationHumidity:pickLocationHumidity andPicLocationTemperature:pickLocationTemperature andPicTemperature:pickTemperature andPicTime:pickTime];

        [picDataArray addObject:pickObj];

    }

    [self.myPickerView reloadComponent:0];

}

json输出如下:

[
    {
        "Date": "2015-02-26",
        "OnDateSensorValues": [
            {
                "Humidity": "49",
                "LocationHumidity": "49",
                "LocationTemperature": "45",
                "Temperature": "45",
                "Time": "10"
            },
            {
                "Humidity": "48",
                "LocationHumidity": "48",
                "LocationTemperature": "44",
                "Temperature": "44",
                "Time": "11"
            },
            {
                "Humidity": "47",
                "LocationHumidity": "47",
                "LocationTemperature": "43",
                "Temperature": "43",
                "Time": "12"
            },
            {
                "Humidity": "46",
                "LocationHumidity": "46",
                "LocationTemperature": "42",
                "Temperature": "42",
                "Time": "13"
            },
            {
                "Humidity": "45",
                "LocationHumidity": "45",
                "LocationTemperature": "41",
                "Temperature": "41",
                "Time": "14"
            }
        ]
    },
    {
        "Date": "2015-02-27",
        "OnDateSensorValues": [
            {
                "Humidity": "29",
                "LocationHumidity": "29",
                "LocationTemperature": "25",
                "Temperature": "25",
                "Time": "6"
            },
            {
                "Humidity": "28",
                "LocationHumidity": "28",
                "LocationTemperature": "24",
                "Temperature": "24",
                "Time": "7"
            },
            {
                "Humidity": "27",
                "LocationHumidity": "27",
                "LocationTemperature": "23",
                "Temperature": "23",
                "Time": "8"
            },
            {
                "Humidity": "26",
                "LocationHumidity": "26",
                "LocationTemperature": "22",
                "Temperature": "22",
                "Time": "9"
            },
            {
                "Humidity": "25",
                "LocationHumidity": "25",
                "LocationTemperature": "21",
                "Temperature": "21",
                "Time": "10"
            }
        ]
    },
    {
        "Date": "2015-02-28",
        "OnDateSensorValues": [
            {
                "Humidity": "31",
                "LocationHumidity": "31",
                "LocationTemperature": "35",
                "Temperature": "35",
                "Time": "22"
            },
            {
                "Humidity": "32",
                "LocationHumidity": "32",
                "LocationTemperature": "36",
                "Temperature": "36",
                "Time": "21"
            },
            {
                "Humidity": "33",
                "LocationHumidity": "33",
                "LocationTemperature": "37",
                "Temperature": "37",
                "Time": "20"
            },
            {
                "Humidity": "34",
                "LocationHumidity": "34",
                "LocationTemperature": "38",
                "Temperature": "38",
                "Time": "19"
            },
            {
                "Humidity": "35",
                "LocationHumidity": "35",
                "LocationTemperature": "39",
                "Temperature": "39",
                "Time": "18"
            }
        ]
    },
    {
        "Date": "2015-03-01",
        "OnDateSensorValues": [
            {
                "Humidity": "12",
                "LocationHumidity": "12",
                "LocationTemperature": "16",
                "Temperature": "16",
                "Time": "2"
            },
            {
                "Humidity": "13",
                "LocationHumidity": "13",
                "LocationTemperature": "17",
                "Temperature": "17",
                "Time": "1"
            },
            {
                "Humidity": "14",
                "LocationHumidity": "14",
                "LocationTemperature": "18",
                "Temperature": "18",
                "Time": "2"
            },
            {
                "Humidity": "15",
                "LocationHumidity": "15",
                "LocationTemperature": "19",
                "Temperature": "19",
                "Time": "3"
            },
            {
                "Humidity": "16",
                "LocationHumidity": "16",
                "LocationTemperature": "20",
                "Temperature": "20",
                "Time": "4"
            }
        ]
    },
    {
        "Date": "2015-03-02",
        "OnDateSensorValues": [
            {
                "Humidity": "32",
                "LocationHumidity": "32",
                "LocationTemperature": "36",
                "Temperature": "36",
                "Time": "20"
            },
            {
                "Humidity": "33",
                "LocationHumidity": "33",
                "LocationTemperature": "37",
                "Temperature": "37",
                "Time": "21"
            },
            {
                "Humidity": "34",
                "LocationHumidity": "34",
                "LocationTemperature": "38",
                "Temperature": "38",
                "Time": "22"
            },
            {
                "Humidity": "35",
                "LocationHumidity": "35",
                "LocationTemperature": "39",
                "Temperature": "39",
                "Time": "23"
            },
            {
                "Humidity": "36",
                "LocationHumidity": "36",
                "LocationTemperature": "40",
                "Temperature": "40",
                "Time": "24"
            }
        ]
    }
]

从这里我想采取临时值,时间值并在图表上显示。但我能够在图表上只绘制一个点。如何在图表上获得所有时间和临时值?....请帮助我,因为我从1周起就在努力解决这个问题。

0 个答案:

没有答案