CorePlot

安装

下载地址:https://code.google.com/p/core-plot/
步骤: 
# Install Binaries for iOS

1. Copy the **CorePlotHeaders** to your Xcode project

2. Copy **libCorePlotCocoaTouch.a** to your Xcode project

3. Add the following flags to "Other Linker Flags" in your target build settings:
   `-ObjC -all_load`

4. Add the **QuartzCore** framework to the project.

5. Add a `CPTGraph` to your application. See the example apps in Source Code to see how, or read the documentation. 

注意:当使用上面的方法,遇到
ld: library not found for -lCorePlot-CocoaTouch 的错误,可以只操作第1和2步,然后将 libCorePlotCocoaTouch.a的名称改为CocoaTouch.a


代码实现

//
//  HJOneDimStatisViewController.m
//  mehr
//
//  Created by 阳君 on 14-5-26.
//  Copyright (c) 2014年 Hjsj. All rights reserved.
//

#import "HJOneDimStatisViewController.h"
#import "HJSetStatisOptionsTableViewController.h"
#import "SVProgressHUD.h"
#import "HJTools.h"
#import "HJEmpQueryViewController.h"

/** 4:初始化*/
NSString *const tInitOneDimStatis = @"4";

// cacheKey
/** 主key*/
NSString *const cOneDimStatis = @"cOneDimStatis";
/** 显示的统计图*/
NSString *const cOneDimStatisCorePlot = @"cOneDimStatisCorePlot";

NSString *const kOneDimStatisName = @"name";
NSString *const kOneDimStatisValue = @"value";

@interface HJOneDimStatisViewController ()
{
@private
    /** 数据源*/
    NSMutableArray *_dataArray;
    /** 总数*/
    NSString *_sum;
    /** 标题*/
    NSString *_titleOneDim;
    
    /** 屏幕高_height;宽:_width*/
    CGFloat _width, _height;
    
    /** 饼图的画板*/
    CPTGraphHostingView *_pieHostingView;
    /** 饼图*/
    CPTPieChart *_piePlot;
    /** CPTPieChart的半径,默认100*/
    CGFloat _pieRadius;
    /** CPTPieChart的旋转角度,默认0.0*/
    CGFloat _startAngle;
    
}

@end

@implementation HJOneDimStatisViewController

#pragma mark 外部传参
- (void)setTitle:(NSString *)title dim:(NSString *)dim condId:(NSString *)condId infokind:(NSString *)infokind cacheDict:(NSMutableDictionary *)cacheDict
{
    _titleOneDim = title;
    self.dim = dim;
    self.condId = condId;
    self.infokind = infokind;
    self.cacheDictionary = cacheDict;
}

-(void)dealloc
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:[NSString stringWithFormat:@"%i", self.plotStyle] forKey:cOneDimStatisCorePlot];
    // 放入数据
    [self.cacheDictionary setObject:dict forKey:cOneDimStatis];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _width = self.view.bounds.size.width;
    _height = self.view.bounds.size.height;
    _pieRadius = 100;
    _startAngle = 0.0;
    
    // 设置查询
    UIBarButtonItem *optionsButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_button_search_options"] style:UIBarButtonItemStylePlain target:self action:@selector(onClick:)];
    optionsButton.tag = 0;
    //统计图类型
    UIBarButtonItem *labelsButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_button_labels"] style:UIBarButtonItemStylePlain target:self action:@selector(onClick:)];
    labelsButton.tag = 1;
    self.navigationItem.rightBarButtonItems = @[optionsButton, labelsButton];
    
    // 参数设置
    NSMutableDictionary *dict = [self.cacheDictionary objectForKey:cOneDimStatis];
    if (dict)
    {
        self.plotStyle = [[dict objectForKey:cOneDimStatisCorePlot] integerValue];
    }
    else
    {
        self.plotStyle = 0;
    }
    [self reloadChart];
    // 初始化数据
    [self initData];
    
}

#pragma mark 点击按钮
- (void)onClick:(UIBarButtonItem *)button
{
    switch (button.tag)
    {
        case 0:// 设置查询
            [self performSegueWithIdentifier:@"one_to_options" sender:self];
            break;
        case 1:
        {
            UIActionSheet *actionSheet = [[UIActionSheet alloc] init];
            actionSheet.title = NSLocalizedString(@"statis_one_dim_type", @"统计图类型");
            actionSheet.delegate = self;
            // actionSheet = [actionSheet initWithTitle:NSLocalizedString(@"statis_one_dim_type", @"统计图类型") delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
            // 添加按钮
            [actionSheet addButtonWithTitle:NSLocalizedString(@"statis_one_dim_bar", @"直方图")];
            [actionSheet addButtonWithTitle:NSLocalizedString(@"statis_one_dim_pie", @"圆饼图")];
            [actionSheet addButtonWithTitle:NSLocalizedString(@"statis_one_dim_scatter", @"折线图")];
            // 添加取消按钮
            [actionSheet addButtonWithTitle:NSLocalizedString(@"cancel", nil)];
            actionSheet.cancelButtonIndex = actionSheet.numberOfButtons - 1;
            actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
            [actionSheet showInView:self.view.window];
            
            break;
        }
    }
    
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 3)
        return;
    self.plotStyle = buttonIndex;
    [self reloadChart];
}

#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // 设置查询
    if ([segue.destinationViewController isKindOfClass:[HJSetStatisOptionsTableViewController class]])
    {
        HJSetStatisOptionsTableViewController *vc = segue.destinationViewController;
        // 传入数据
        [vc setTarget:self cacheDict:self.cacheDictionary];
    }
    
}

#pragma mark - 初始化数据
- (void)initData
{
    // 初始化
    HJTask *task = [[HJTask alloc] initWithFuncId:@"9102006001"];
    [task addParamter:@"transType" obj:tInitOneDimStatis];
    [task addParamter:@"condid" obj:self.condId];
    [task addParamter:@"dim" obj:self.dim];
    [task addParamter:@"infokind" obj:self.infokind];
    // 增加设置范围的参数
    [HJSetStatisOptionsTableViewController addTaskParamter:task cacheDict:self.cacheDictionary];
    
    [task sendRequestWithDelegate:self];
    
}

#pragma mark HJTaskRunnerDelegate
-(void)execute:(NSMutableDictionary *)values
{
    NSString *succeed = [values objectForKey:@"succeed"];
    if ([@"true" isEqualToString:succeed])
    {
        _dataArray = [values objectForKey:@"oneList"];
        if (_dataArray.count > 0)
        {
            NSDictionary *item = [_dataArray objectAtIndex:_dataArray.count - 1];
            _sum = [item objectForKey:@"sum"];
            self.title = [NSString stringWithFormat:@"%@(%@)", _titleOneDim, _sum];
            [_dataArray removeLastObject];
        }
        [self reloadChart];
        
        
    }
    else
    {
        NSString *message = [values valueForKey:@"message"];
        if (message)
        {
            [SVProgressHUD showErrorWithStatus:message];
        }
        else
        {
            [HJTools showErrorMessageBox:1005];//提示远程服务出错啦
        }
    }
}

- (void)passvalue:(NSMutableDictionary *)values
{
    [self initData];
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    // 返回yes,多个手势同时工作
    return YES;
}

#pragma mark 图形捏合
- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer
{
    _piePlot.pieRadius = _pieRadius * recognizer.scale;
    // 缩放完毕,记住新的半径大小
    if (recognizer.state == UIGestureRecognizerStateEnded)
    {
        _pieRadius = _piePlot.pieRadius;
    }
}

#pragma mark 图形旋转
- (void)handleRotation:(UIRotationGestureRecognizer *)recognizer
{
    _piePlot.startAngle = _startAngle - recognizer.rotation;
    // 旋转完毕,记住新的旋转角度
    if (recognizer.state == UIGestureRecognizerStateEnded)
    {
        _startAngle = _piePlot.startAngle;
    }
}

#pragma mark 图形移动
- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
    // 取点
    CGPoint translatedPoint = [recognizer translationInView:_pieHostingView];
    // 计算
    CGFloat x = recognizer.view.center.x + translatedPoint.x;
    CGFloat y = recognizer.view.center.y + translatedPoint.y;
    // 移动范围
    x = x < 0 ? 0 : x;
    y = y < 0 ? 0 : y;
    x = x > _width ? _width : x;
    y = y > _height ? _height : y;
    // 移动
    recognizer.view.center = CGPointMake(x, y);
    // 回归中心点
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}

#pragma mark - 刷新视图
- (void)reloadChart
{
    // 清楚上个视图
    CPTGraphHostingView *cptHostingView = (CPTGraphHostingView *)[self.view viewWithTag:888];
    [cptHostingView removeFromSuperview];
    // 刷新
    switch (self.plotStyle)
    {
        case HJOneDimStatisPlotStyleBar://直方图
            [self reloadBarChart];
            break;
        case HJOneDimStatisPlotStylePie:// 圆饼图
            [self reloadPieChart];
            break;
        case HJOneDimStatisPlotStyleScatter:// 折线图
            [self reloadScatterChart];
            break;
    }
}

#pragma mark 刷新柱状图
- (void)reloadBarChart
{
    // 创建画板
    CPTGraphHostingView *cptHostingView = [[CPTGraphHostingView alloc] initWithFrame:CGRectMake(0, 0,_width, _height - 50)];
    cptHostingView.tag = 888;
    [self.view addSubview:cptHostingView];
    
    // 画布
    CPTXYGraph *graph=[[CPTXYGraph alloc] initWithFrame:cptHostingView.bounds];
    graph.plotAreaFrame.masksToBorder = NO;
    cptHostingView.hostedGraph = graph;
    // 界面样式
    [graph applyTheme:[CPTTheme themeNamed:kCPTPlainWhiteTheme]];
    // graph在hostingView中的偏移
    graph.paddingBottom = 60;
    graph.paddingLeft   = 40;
    graph.paddingRight  = 5;
    graph.paddingTop    = 5;
    graph.plotAreaFrame.borderLineStyle = nil;
    graph.plotAreaFrame.cornerRadius = 0.0f;// hide frame
/**
     // 绘图区4边留白
     graph.plotAreaFrame.paddingTop    = 5;
     graph.plotAreaFrame.paddingRight  = 5;
     graph.plotAreaFrame.paddingLeft   = 20;
     graph.plotAreaFrame.paddingBottom = 5;
*/
    
    // 设置间隔
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0) length:CPTDecimalFromInteger(_dataArray.count + 1)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0) length:CPTDecimalFromInteger([_sum integerValue] / 3 * 2)];
    // 放大缩小滚动
    plotSpace.allowsUserInteraction = YES;
    
    // 线条样式
    CPTMutableLineStyle *lineStyle = [[CPTMutableLineStyle alloc] init];
    lineStyle.lineColor = [CPTColor blackColor];
    lineStyle.lineWidth = 1.0;
    
    // 设置x、y轴
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    // xAxis
    CPTXYAxis *xAxis = axisSet.xAxis;
    {
        xAxis.axisLineStyle  = lineStyle;
        xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
        
        xAxis.majorTickLineStyle  = lineStyle; //X轴大刻度线,线型设置
        xAxis.majorTickLength     = 5;  // 刻度线的长度
        xAxis.majorIntervalLength = CPTDecimalFromInt(1); // 间隔单位,和xMin~xMax对应
        // 小刻度线minor...
        xAxis.minorTickLineStyle = nil;
        xAxis.orthogonalCoordinateDecimal = CPTDecimalFromInt(0);
        // 设置X轴label
        NSMutableArray *labelArray = [NSMutableArray arrayWithCapacity:7];
        // 当显示的个数大于大于4时,倾斜
        BOOL rotationlable = _dataArray.count >= 4 ? YES : NO;
        NSDictionary *item;
        NSString *xTitle = @"";;
        NSString *maxTitle = @"";
        for (int i = 0; i < _dataArray.count; i++)
        {
            item = [_dataArray objectAtIndex:i];
            xTitle = [item objectForKey:kOneDimStatisName];
            CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:xTitle textStyle:xAxis.labelTextStyle];
            newLabel.tickLocation = [[NSNumber numberWithInt:i + 1] decimalValue];
            newLabel.offset = xAxis.labelOffset + xAxis.majorTickLength;
            
            // 倾斜
            if (rotationlable)
            {
                // 取30度角度
                newLabel.rotation = M_PI/6;
                NSLog(@"-----------%f", newLabel.offset);
                maxTitle = maxTitle.length > xTitle.length ? maxTitle : xTitle;
            }
            [labelArray addObject:newLabel];
            
        }
        // 加上这两句才能显示label
        xAxis.axisConstraints =[CPTConstraints constraintWithLowerOffset:0.0];
        // 显示的标题
        xAxis.axisLabels=[NSSet setWithArray:labelArray];
        
        // 倾斜
        if (rotationlable)
        {
            CGSize textSize = [maxTitle sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(320, 30) lineBreakMode:NSLineBreakByCharWrapping];
            NSInteger height = (int)textSize.width / 2 + 20;
            CGRect frame = cptHostingView.frame;
            frame.size = CGSizeMake(_width, _height - height);
            cptHostingView.frame = frame;
        }
    }
    
    // yAxis
    CPTXYAxis *yAxis = axisSet.yAxis;
    {
        yAxis.axisLineStyle = lineStyle;
        yAxis.minorTickLineStyle = nil;  //  不显示小刻度线
        yAxis.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
        
        // 显示y轴
        yAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:0];
        // y轴字体大小
        yAxis.labelOffset     = 10;
        
        // 将y轴显示的0.0变为0
        NSNumberFormatter *labelFormatter    = [[NSNumberFormatter alloc] init];
        labelFormatter.maximumFractionDigits = 0;
        yAxis.labelFormatter                 = labelFormatter;
    }
    
    // set up the plots
    CPTBarPlot *barPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:NO];
    
    barPlot.dataSource = self;
    // 如果不需要柱状图的选择,这条语句是没必要的
    barPlot.delegate = self;
    // 设定基值,大于该值的从此点向上画,小于该值的反向绘制,即向下画
    barPlot.baseValue = CPTDecimalFromInt(0);
    // 设定柱图的宽度(0.0~1.0)
    barPlot.barWidth =CPTDecimalFromDouble(0.5);
    // 柱图每个柱子开始绘制的偏移位置,我们让它绘制在刻度线中间,所以不偏移
    barPlot.barOffset = CPTDecimalFromDouble(-0.0);
    barPlot.lineStyle = lineStyle;
    
    // 将plot添加到默认的空间中
    [graph addPlot:barPlot toPlotSpace:graph.defaultPlotSpace];
}

#pragma mark 刷新饼图
- (void)reloadPieChart
{
    // 创建画板
    _pieHostingView = [[CPTGraphHostingView alloc] initWithFrame:CGRectMake(-100, -15, _width + 200, _height + 30)];
    _pieHostingView.tag = 888;
    [self.view addSubview:_pieHostingView];
    
    // 创建画布
    CPTXYGraph *graph = [[CPTXYGraph alloc ] initWithFrame:self.view.bounds];
    // 设置画板的画布
    _pieHostingView.hostedGraph = graph;
    // 设置画布主题
    CPTTheme *theme = [CPTTheme themeNamed:kCPTPlainWhiteTheme];
    [graph applyTheme :theme];
    // 将画布的坐标轴设为空
    graph.axisSet = nil;

    // 创建饼图对象
    _piePlot = [[ CPTPieChart alloc ] initWithFrame:CGRectMake(0, 0, _width, _height)];
    // 将饼图加到画布上
    [graph addPlot:_piePlot];
    // 设置数据源
    _piePlot.dataSource = self;
    // 设置饼图半径
    _piePlot.pieRadius  = _pieRadius;
    // 设置饼图表示符
    _piePlot.identifier = @"pie chart";
    // 饼图开始绘制的位置
    _piePlot.startAngle = _startAngle;
    
    // 饼图绘制的方向(顺时针 / 逆时针)
    _piePlot.sliceDirection = CPTPieDirectionCounterClockwise;
    // 饼图的重心
    _piePlot.centerAnchor = CGPointMake(0.5, 0.5);
    
    // 饼图的线条风格
    // piePlot.borderLineStyle = [CPTLineStyle lineStyle];
    
    // 设置代理
    _piePlot.delegate = self ;
    
    // 渐变效果
    CPTGradient *overlayGradient = [[CPTGradient alloc] init];
    overlayGradient.gradientType = CPTGradientTypeRadial;
    overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.0] atPosition:0.9];
    overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.4] atPosition:1.0];
    _piePlot.overlayFill = [CPTFill fillWithGradient:overlayGradient];
    
    // 手势操作
    // 移动
    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [_pieHostingView addGestureRecognizer:panRecognizer];
    
    // 缩放
    UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
    pinchRecognizer.delegate = self;
    [_pieHostingView addGestureRecognizer:pinchRecognizer];
    
    // 旋转
    UIRotationGestureRecognizer *rotationRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)];
    rotationRecognizer.delegate = self;
    [_pieHostingView addGestureRecognizer:rotationRecognizer];
    
}

#pragma mark 折线图
- (void)reloadScatterChart
{
    // 设置画板边框大小
    CPTGraphHostingView *cptHostingView = [[CPTGraphHostingView alloc] initWithFrame:CGRectMake(0, 0,_width, _height - 50)];
    cptHostingView.tag = 888;
    [self.view addSubview:cptHostingView];
    
    // 画布
    CPTXYGraph *graph=[[CPTXYGraph alloc] initWithFrame:cptHostingView.bounds];
    graph.plotAreaFrame.masksToBorder = NO;
    cptHostingView.hostedGraph = graph;
    // 界面样式
    [graph applyTheme:[CPTTheme themeNamed:kCPTPlainWhiteTheme]];
    // graph在hostingView中的偏移
    graph.paddingBottom = 60;
    graph.paddingLeft   = 40;
    graph.paddingRight  = 5;
    graph.paddingTop    = 5;
    graph.plotAreaFrame.borderLineStyle = nil;
    graph.plotAreaFrame.cornerRadius = 0.0f;// hide frame
/**
    // 绘图区4边留白
    graph.plotAreaFrame.paddingTop    = 5;
    graph.plotAreaFrame.paddingRight  = 5;
    graph.plotAreaFrame.paddingLeft   = 20;
    graph.plotAreaFrame.paddingBottom = 5;
*/
    
    // 设置间隔
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0) length:CPTDecimalFromInteger(_dataArray.count + 1)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0) length:CPTDecimalFromInteger([_sum integerValue] / 3 * 2)];
    // 放大缩小滚动
    plotSpace.allowsUserInteraction = YES;
    
    // 线条样式
    CPTMutableLineStyle *lineStyle = [[CPTMutableLineStyle alloc] init];
    lineStyle.lineColor = [CPTColor blackColor];
    lineStyle.lineWidth = 1.0;
    
    // 设置x、y轴
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    // xAxis
    CPTXYAxis *xAxis = axisSet.xAxis;
    {
        xAxis.axisLineStyle  = lineStyle;
        xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
        
        xAxis.majorTickLineStyle  = lineStyle; //X轴大刻度线,线型设置
        xAxis.majorTickLength     = 5;  // 刻度线的长度
        xAxis.majorIntervalLength = CPTDecimalFromInt(1); // 间隔单位,和xMin~xMax对应
        // 小刻度线minor...
        xAxis.minorTickLineStyle = nil;
        xAxis.orthogonalCoordinateDecimal = CPTDecimalFromInt(0);
        // 设置X轴label
        NSMutableArray *labelArray = [NSMutableArray arrayWithCapacity:7];
        // 当显示的个数大于大于4时,倾斜
        BOOL rotationlable = _dataArray.count >= 4 ? YES : NO;
        NSDictionary *item;
        NSString *xTitle = @"";;
        NSString *maxTitle = @"";
        for (int i = 0; i < _dataArray.count; i++)
        {
            item = [_dataArray objectAtIndex:i];
            xTitle = [item objectForKey:kOneDimStatisName];
            CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:xTitle textStyle:xAxis.labelTextStyle];
            newLabel.tickLocation = [[NSNumber numberWithInt:i + 1] decimalValue];
            newLabel.offset = xAxis.labelOffset + xAxis.majorTickLength;
            
            // 倾斜
            if (rotationlable)
            {
                // 取30度角度
                newLabel.rotation = M_PI/6;
                maxTitle = maxTitle.length > xTitle.length ? maxTitle : xTitle;
            }
            [labelArray addObject:newLabel];
            
        }
        // 加上这两句才能显示label
        xAxis.axisConstraints =[CPTConstraints constraintWithLowerOffset:0.0];
        // 显示的标题
        xAxis.axisLabels=[NSSet setWithArray:labelArray];
        
        // 倾斜
        if (rotationlable)
        {
            CGSize textSize = [maxTitle sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(320, 30) lineBreakMode:NSLineBreakByCharWrapping];
            NSInteger height = (int)textSize.width / 2 + 20;
            CGRect frame = cptHostingView.frame;
            frame.size = CGSizeMake(_width, _height - height);
            cptHostingView.frame = frame;
        }
        
    }
    
    // yAxis
    CPTXYAxis *yAxis = axisSet.yAxis;
    {
        yAxis.axisLineStyle = lineStyle;
        yAxis.minorTickLineStyle = nil;  //  不显示小刻度线
        yAxis.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
        
        // 显示y轴
        yAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:0];
        // y轴字体大小
        yAxis.labelOffset     = 10;
        
        // 将y轴显示的0.0变为0
        NSNumberFormatter *labelFormatter    = [[NSNumberFormatter alloc] init];
        labelFormatter.maximumFractionDigits = 0;
        yAxis.labelFormatter                 = labelFormatter;
    }
    
    // Set axes
    graph.axisSet.axes = [NSArray arrayWithObjects:xAxis, yAxis, nil];
    
    // Create a plot that uses the data source method
    CPTScatterPlot *scatterPlot            = [[CPTScatterPlot alloc] init];
    scatterPlot.identifier = @"Data Source Plot";
    scatterPlot.dataSource = self;
    scatterPlot.delegate = self;
    [graph addPlot:scatterPlot];
    // Set plot delegate, to know when symbols have been touched
    // We will display an annotation when a symbol is touched
    scatterPlot.plotSymbolMarginForHitDetection = 5.0;
    
    // 绿色的连线
    CPTMutableLineStyle *connectLineStyle = [scatterPlot.dataLineStyle mutableCopy];
    connectLineStyle.lineWidth            = 3.0;
    connectLineStyle.lineColor            = [CPTColor greenColor];
    scatterPlot.dataLineStyle             = connectLineStyle;
    
    // 折线点
    CPTMutableLineStyle *symbolLineStyle = [CPTMutableLineStyle lineStyle];
    symbolLineStyle.lineColor = [CPTColor blackColor];
    CPTPlotSymbol *plotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
    plotSymbol.fill           = [CPTFill fillWithColor:[CPTColor blueColor]];
    plotSymbol.lineStyle      = symbolLineStyle;
    plotSymbol.size           = CGSizeMake(10.0, 10.0);
    scatterPlot.plotSymbol    = plotSymbol;
    
    // 全画布显示
    // [plotSpace scaleToFitPlots:[NSArray arrayWithObjects:dataSourceLinePlot, nil]];
    
}

#pragma mark - CPTPlotDataSource
#pragma mark 返回数目
- ( NSUInteger )numberOfRecordsForPlot:( CPTPlot *)plot

{
    return _dataArray.count;
}

#pragma mark 标题
- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    NSNumber *num;
    NSDictionary *item = [_dataArray objectAtIndex:index];
    
    switch (self.plotStyle)
    {
        case HJOneDimStatisPlotStyleBar://直方图
        case HJOneDimStatisPlotStyleScatter:// 折线图
        {
            switch ( fieldEnum )
            {
                    case CPTBarPlotFieldBarLocation:// X轴上的数值表示
                    num = [NSNumber numberWithInt:index + 1];
                    break;
                case CPTBarPlotFieldBarTip:// y轴上的数值表示
                    num = [NSDecimalNumber numberWithInt:[[item objectForKey:kOneDimStatisValue] intValue]];
                    break;
            }
            break;
        }
        case HJOneDimStatisPlotStylePie:// 圆饼图
        {
            float result = [[item objectForKey:kOneDimStatisValue] floatValue] / [_sum floatValue];
            num = [NSNumber numberWithFloat:result];
            break;
        }

    }
    
    return num;
}

#pragma mark 返回每个扇形的标题
- ( CPTLayer *)dataLabelForPlot:( CPTPlot *)plot recordIndex:( NSUInteger )idx

{
    // 描述
    NSDictionary *item = [_dataArray objectAtIndex:idx];
    NSString *textStr;
    switch (self.plotStyle)
    {
        case HJOneDimStatisPlotStylePie:
        {
            float result = [[item objectForKey:kOneDimStatisValue] floatValue] / [_sum floatValue];
            textStr = [NSString stringWithFormat:@"%@\n(%.2f,值:%@)", [item objectForKey:kOneDimStatisName], result, [item objectForKey:kOneDimStatisValue]];
            break;
        }
        default:
            textStr = [item objectForKey:kOneDimStatisValue];
            break;
    }
   
    // 字体样式
    static CPTMutableTextStyle *text;
    if ( !text )
    {
        text = [[CPTMutableTextStyle alloc] init];
        //text.color = [CPTColor darkGrayColor];
        text.textAlignment = NSTextAlignmentCenter;
        text.fontSize = 12;
    }
    
    // 标题
    CPTTextLayer *newLayer = [[CPTTextLayer alloc] initWithText:textStr style:text];
    
    return newLayer;

}

#pragma mark - CPTPieChartDelegate 选中某个扇形时的操作
- (void)pieChart:(CPTPieChart *)plot sliceWasSelectedAtRecordIndex:(NSUInteger)idx
{
   [self jumpToEmpWithSelectedAtRecordIndex:idx];
}

#pragma mark - CPTBarPlotDelegate 点击bar
- (void)barPlot:(CPTBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)idx
{
    [self jumpToEmpWithSelectedAtRecordIndex:idx];
}

#pragma mark - CPTBarPlotDataSource bar的颜色
-(CPTFill *)barFillForBarPlot:(CPTBarPlot *)barPlot recordIndex:(NSUInteger)index
{
    
    NSArray *array = [NSArray arrayWithObjects:[CPTColor redColor], [CPTColor orangeColor], [CPTColor yellowColor], [CPTColor greenColor], [CPTColor blueColor], [CPTColor cyanColor], [CPTColor purpleColor], nil];
    //
    index = index % array.count;
    CPTColor *color = [array objectAtIndex:index];
    
    CPTGradient *fillGradient = [CPTGradient gradientWithBeginningColor:color endingColor:[CPTColor blackColor]];
    
    return [CPTFill fillWithGradient:fillGradient];
}

#pragma mark - CPTBarPlotDelegate 点击scatter
- (void)scatterPlot:(CPTScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)idx
{
    [self jumpToEmpWithSelectedAtRecordIndex:idx];
}

#pragma mark - 跳转
- (void)jumpToEmpWithSelectedAtRecordIndex:(NSUInteger)index
{
    NSDictionary *item = [_dataArray objectAtIndex:index];
    //新的进入
    NSMutableDictionary *taskDictionary = [NSMutableDictionary dictionaryWithCapacity:3];
    [taskDictionary setObject:self.dim forKey:@"statisDim"];
    [taskDictionary setObject:[item objectForKey:@"id"] forKey:@"statisSLegendID"];
    [taskDictionary setObject:self.infokind forKey:@"statisInfokind"];
    [taskDictionary setObject:@"statis" forKey:@"querytype"];
    
    [HJSetStatisOptionsTableViewController addJumpToEmpDictionary:taskDictionary cacheDict:self.cacheDictionary];
    

    HJEmpQueryViewController *emp = [HJEmpQueryViewController empQueryViewControllerWithTitle:[item objectForKey:@"name"] taskDictionary:taskDictionary viewStyle:HJEmpQueryStyleDefault];
    emp.viewStyle = HJEmpQueryStyleOther;
    [self.navigationController pushViewController:emp animated:YES];

}

@end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值