2013-06-29 3 views
0

Я попытался построить операцию с использованием названия месяцев с некоторыми данными по оси y. Я хотел, чтобы у показать данные, такие как 20, 40, 50, 60, ... 120, а х должен был быть только январь, февраль, март Это то, что я хочудиаграмма разметки основного участка графика x y не отображается правильно

Click This link here

и это то, что я получаю

Click This link here Кто-то знает, как исправить это, пожалуйста?

xValues, Y. только NSMutables с данными xValues ​​[0, 5, 15, 20 ... 50 ... 60 ... 70 ..] [60, Y., 70, 80, 50, 40 ....]

коды ниже

#import <Foundation/Foundation.h> 

    @interface GraphManager_ : NSObject<CPTPlotDataSource> 
    @property (strong, nonatomic)CPTGraphHostingView *hostView; 
    @property (strong, nonatomic)UIView *plotContainerView; 
    @property (strong, nonatomic)NSMutableArray *xValue; 
    @property (strong, nonatomic)NSMutableArray *yValue; 
    @property (strong, nonatomic)NSString *plotTitle; 


-(id) initScatterPlot:(UIView *)plotContainerView plotTitle:(NSString *)plotTitle xValue:(NSMutableArray *)xValues yValues:(NSMutableArray *) yValues; 

-(void)configureGraph; 
-(void)configureXAxis; 
-(void)configureYAxis; 
-(void)configurePlot; 
-(void)drawScatterPlot; 

@end 


#import "GraphManager_.h" 

@implementation GraphManager_ 

@synthesize plotContainerView = _plotContainerView; 
@synthesize plotTitle = _plotTitle; 
@synthesize hostView = _hostView; 
@synthesize xValue = _xValues; 
@synthesize yValue = _yValues; 


-(id)initScatterPlot:(UIView *)plotContainerView plotTitle:(NSString *)plotTitle xValue: (NSMutableArray *)xValues yValues:(NSMutableArray *)yValues{ 

    self = [super init]; 
    if(self){ 
     self.plotContainerView = plotContainerView; 
     self.plotTitle = plotTitle; 
     self.xValue = xValues; 
     self.yValue = yValues; 
    } 
    return self; 

    } 



-(void)configureGraph{ 


    CGRect plotContainerViewBound = _plotContainerView.bounds; 
plotContainerViewBound = CGRectMake(_plotContainerView.frame.origin.x, _plotContainerView.frame.origin.y, 1025, 560); 

    _hostView = [[CPTGraphHostingView alloc] initWithFrame:plotContainerViewBound]; 
    _hostView.backgroundColor = [UIColor blackColor]; 
    [_plotContainerView addSubview:_hostView]; 

    CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:_hostView.bounds]; 
    [graph applyTheme:[CPTTheme themeNamed:kCPTPlainBlackTheme]]; 
    _hostView.hostedGraph = graph; 

    //tweaking the graph 
    graph.paddingTop = 30.0f; 
    graph.paddingBottom = 30.0f; 
    graph.paddingLeft = 30.0f; 
    graph.paddingRight = 30.0f; 

    graph.titleTextStyle = [self textStyle]; 
    graph.title = _plotTitle; 

    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop; 
    graph.titleDisplacement = CGPointMake(0.0f, 4.0f); 

    graph.plotAreaFrame.paddingTop = 20.0f; 
    graph.plotAreaFrame.paddingBottom = 40.0f; 
    graph.plotAreaFrame.paddingLeft = 40.0f; 
    graph.plotAreaFrame.paddingRight = 40.0f; 

    graph.plotAreaFrame.borderColor = nil; 

    graph.plotAreaFrame.plotArea.fill = [[CPTFill alloc] initWithColor:[CPTColor colorWithComponentRed:23.0f/255.0f green:38.0f/255.0f blue:57.0f/255.0f alpha:1.0]]; 

} 

-(void)configureYAxis{ 

    NSNumberFormatter *yAxisLabelFormatter = [[NSNumberFormatter alloc] init]; 
    [yAxisLabelFormatter setNumberStyle:NSNumberFormatterNoStyle]; 

    //configuring the x and y axis 
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)_hostView.hostedGraph.graph.axisSet; 
    CPTXYAxis *y = axisSet.yAxis; 
    y.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0f]; 
    y.majorIntervalLength = [[NSNumber numberWithInt:20] decimalValue]; 
    y.labelFormatter = yAxisLabelFormatter; 
    y.majorGridLineStyle = [self xyGridLineStyle]; 
    y.axisLineStyle = [self xyGridLineStyle]; 
    y.tickDirection = CPTSignNegative; 
    y.majorTickLength = 0.0f; 
    y.minorTickLength = 0.0f; 
} 

-(void)configureXAxis{ 
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)_hostView.hostedGraph.axisSet; 
    CPTXYAxis *x = axisSet.xAxis; 
    x.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0f]; 
    x.majorIntervalLength = [[NSNumber numberWithInt:1] decimalValue];//to be taken outside 
    //x.labelFormatter = yAxisLabelFormatter; 
    x.majorGridLineStyle = [self xyGridLineStyle]; 
    x.axisLineStyle = [self xyGridLineStyle]; 
    x.tickDirection = CPTSignNegative; 
    x.majorTickLength = 0.0f; 
    x.minorTickLength = 0.0f; 
    x.majorTickLocations = [self majorXTickLocations]; 
    x.axisLabels = [self smallMonthLabels]; 
    x.labelingPolicy = CPTAxisLabelingPolicyNone; 
} 

-(void)configurePlot{ 

    CPTScatterPlot *plot = [[CPTScatterPlot alloc] initWithFrame:CGRectZero]; 
    plot.dataSource = self; 

    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)_hostView.hostedGraph.graph.defaultPlotSpace; 
    [plotSpace scaleToFitPlots:[NSArray arrayWithObjects:plot,nil]]; 
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(120.0)]; 
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(50.0)]; 

    CPTMutableLineStyle *plotLineStyle = [plot.dataLineStyle mutableCopy]; 
    plotLineStyle.lineColor = [CPTColor colorWithComponentRed:63.0f/255.0f green:241.0f/255.0f blue:124.0f/255.0f alpha:1.0]; 
    plotLineStyle.lineWidth = 5.0f; 
    plot.dataLineStyle = plotLineStyle; 

    CPTPlotSymbol *plotSymbol = [CPTPlotSymbol ellipsePlotSymbol]; 
    plotSymbol.fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:51.0f/255.0f green:153.0f/255.0f blue:51.0f/255.0f alpha:1.0]]; 
    plotSymbol.size = CGSizeMake(5.0f, 5.0f); 
    plotSymbol.lineStyle = plotLineStyle; 
    plot.plotSymbol = plotSymbol; 
    [_hostView.hostedGraph.graph addPlot:plot toPlotSpace:_hostView.hostedGraph.graph.defaultPlotSpace]; 

} 

-(void)drawScatterPlot{ 


    [self configureGraph]; 

    [self configureYAxis]; 

    [self configureXAxis]; 

    [self configurePlot]; 
} 

-(NSSet *)customAxisLabels:(NSArray *)customLabelSet{ 

    CPTMutableTextStyle *textStyle = [[CPTMutableTextStyle alloc] init]; 
    textStyle.color = [CPTColor whiteColor]; 
    textStyle.fontName = @"Helvetica-Bold"; 
    textStyle.fontSize = 18.0f; 

    NSMutableArray *customTickLocations = [[NSMutableArray alloc] initWithCapacity:_xValues.count]; 

    for(int i=0; i < _xValues.count; i++){ 
    [customTickLocations addObject:[_xValues objectAtIndex:i]]; 
    } 

    NSMutableSet *customLabel = [[NSMutableSet alloc] initWithCapacity:customTickLocations.count]; 


    for(int i = 0; i<[customTickLocations count] -1; i++){ 
     NSNumber *tickLocation = [customTickLocations objectAtIndex:i]; 

     CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:@"%@", [customLabelSet objectAtIndex:i]] textStyle:textStyle]; 
     newLabel.tickLocation = [tickLocation decimalValue]; 
     [customLabel addObject:newLabel]; 
    } 

    return customLabel; 
} 

-(CPTMutableTextStyle *)textStyle{ 
    //text styles 
    CPTMutableTextStyle *textStyle = [[CPTMutableTextStyle alloc] init]; 
    textStyle.color = [CPTColor whiteColor]; 
    textStyle.fontName = @"Helvetica-Bold"; 
    textStyle.fontSize = 18.0f; 

    return textStyle; 
} 

-(CPTMutableLineStyle *)xyGridLineStyle{ 

//xy grid line style 
    CPTMutableLineStyle *xyGridLineStyle = [CPTMutableLineStyle lineStyle]; 
    xyGridLineStyle.lineColor = [CPTColor colorWithComponentRed:25.0f/255.0f green:60.0f/255.0f blue:94.0f/255.0f alpha:1.0]; 
    xyGridLineStyle.lineWidth = 0.50f; 
    return xyGridLineStyle; 
} 

-(NSSet *) majorXTickLocations{ 
    return [[NSSet alloc] initWithArray:_xValues]; 
} 

-(NSSet *)majorYTickLocations{ 
    return [[NSSet alloc] initWithArray:_yValues]; 
} 

-(NSSet *)smallMonthLabels{ 
    NSArray *shortenedMonthNames = [NSArray arrayWithObjects:@"Jan", @"Feb", @"Mar", @"Apr", @"May", @"Jun", @"Jul", @"Aug", @"Sep",@"Oct", @"Nov", @"Dec", nil]; 

    return [self customAxisLabels:shortenedMonthNames]; 

} 

-(NSSet *)amPmTimeLabels{ 
     NSArray *ampmSet = [NSArray arrayWithObjects:@"12am",@"1", @"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11", @"Noon",@"1",@"2", @"3", @"4", @"5",@"6", @"7", @"8", @"9",@"10", @"11pm", nil]; 
     return [self customAxisLabels:ampmSet]; 
} 

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

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx{ 
     if(fieldEnum == CPTScatterPlotFieldX){ 
     return [self.xValue objectAtIndex:idx]; 
     }else{ 
     return [self.yValue objectAtIndex:idx]; 
    } 

} 
@end 


#import <UIKit/UIKit.h> 
#import "GraphManager_.h" 
#import "GraphDataManager.h" 

@interface testVC_ : UIViewController 

@property (strong, nonatomic) IBOutlet UIView *dailyRateGraphView; 
@property (strong, nonatomic) GraphManager_ *graphManager; 
@property (strong, nonatomic) GraphDataManager *graphDataManager; 

@end 


#import "testVC_.h" 

@interface testVC_() 

@end 

@implementation testVC_ 



- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
// Do any additional setup after loading the view. 
    self.graphDataManager = [GraphDataManager sharedInstance]; 
    [self.graphDataManager getDailyHeartRateData]; 

     self.graphManager = [[GraphManager_ alloc] initScatterPlot:self.dailyRateGraphView 
               plotTitle:@"Sample Data" 
                  xValue:self.graphDataManager.xAxisLabelValues 
                yValues:self.graphDataManager.yAxisLabelValues]; 
     [self.graphManager drawScatterPlot]; 
    } 

    - (void)didReceiveMemoryWarning 
    { 
     [super didReceiveMemoryWarning]; 
     // Dispose of any resources that can be recreated. 
    } 

@end 
+0

Я предполагаю, что вы вызываете '-drawScatterPlot', чтобы настроить все, не так ли? Вызывается ли источник данных? –

+0

Да @EricSkroch. Я вызываю -drawScatterPlot, чтобы нарисовать сюжет. Это должно быть потому, что, как вы можете видеть в ссылке на изображение, которую я опубликовал, я получаю первое значение «Ян» по оси x –

+0

Я не вижу никаких очевидных проблем в коде, который вы опубликовали. Однако диапазоны пространственных пространств не меняются от значения по умолчанию [0, 1]. Сосредоточьте свое устранение неполадок вокруг этого факта Одно предложение: поскольку вы все равно используете пространство по умолчанию, попробуйте '[_hostView.hostedGraph.graph addPlot: plot];'. Он должен быть эквивалентен вашему коду, но стоит попробовать. –

ответ

0

Изменить любые ссылки на _hostView.hostedGraph.graph к _hostView.hostedGraph. Свойство наследуется от CPTLayer. Он используется другими частями графика для сохранения указателя на график, но не самого графика.

+0

Спасибо! в мои выходные. Это помогло исправить оси x и y, но теперь значения инвертируются [Посмотрите здесь] (https://twitter.com/jsoniz/status/351368186832252928/photo/1), что произошло. Ось x и y инвертированная вниз сторона –

+0

Хостинг iOS отображает свой размещенный слой (график), поэтому мы можем использовать один и тот же код чертежа на Mac и iOS. Проверьте свою иерархию представлений и убедитесь, что у вас нет (например) одного вида хостинга внутри другой. –

+0

Да, это тоже помогло. Спасибо @ Эрик –