1. 程式人生 > >CorePlot_1.5.1 繪製散點圖(折線圖、曲線圖、直方圖)

CorePlot_1.5.1 繪製散點圖(折線圖、曲線圖、直方圖)

前言

CorePlot提供了散點圖(CPTScatterPlot)的繪製,包括:折線圖、曲線圖、直方圖。如下圖所示:

  

 

CorePlot框架自身提供了線條樣式、文字樣式及填充色的設定。CPTMutableLineStyle/CPTLineStyle用於設定線條樣式;CPTMutableTextStyle/CPTTextStyle用於設定文字樣式;CPTFill用於設定填充色。

資料來源及x軸的標籤:

NSMutableArray *dataSource = [NSMutableArray arrayWithCapacity:10];
for (int i = 0; i < 10; i++) {
    [dataSource addObject:@(arc4random()%10)];
}
self.dataSource = dataSource;
_coordinatesX = @[@"第一次",@"第二次",@"第三次",@"第四次",@"第五次",@"第六次",@"第七次",@"第八次",@"第九次",@"第十次"];

宿主View(CPTGraphHostingView)的建立

CorePlot中的所有圖表都是繪製在宿主View中的,其他普通View無法繪製圖標。CPTGraphHostingView繼承自UIView。

#pragma mark 建立宿主HostView
- (void)createHostView
{
    //  圖形要放在CPTGraphHostingView宿主中,因為UIView無法載入CPTGraph
    _hostView = [[CPTGraphHostingView alloc] initWithFrame:self.bounds];
    //  預設值:NO,設定為YES可以減少GPU的使用,但是渲染圖形的時候會變慢
    _hostView.collapsesLayers = NO;
    //  允許捏合縮放 預設值:YES
    _hostView.allowPinchScaling = NO;
    //  背景色 預設值:clearColor
    _hostView.backgroundColor = [UIColor whiteColor];
    
    // 新增到View中
    [self addSubview:_hostView];
}

畫布(CPTXYGraph)的建立

CPTXYGraph繼承自CPTGraph。CPTXYGraph是繪製帶有x、y軸座標的圖示。CPTGraph管理繪圖空間、繪圖區域、座標軸、標籤、標題等的建立。

#pragma mark 建立圖表,用於顯示的畫布
- (void)createGraph
{
    // 基於xy軸的圖表建立
    CPTXYGraph *graph=[[CPTXYGraph alloc] initWithFrame:_hostView.bounds];
    // 使宿主檢視的hostedGraph與CPTGraph關聯
    _hostView.hostedGraph = graph;
    
    // 設定主題,類似於面板
    {
        //CPTTheme *theme = [CPTTheme themeNamed:kCPTSlateTheme];
        //[graph applyTheme:theme];
    }
    
    // 標題設定
    {
        graph.title = @"標題:曲線圖";
        // 標題對齊於圖框的位置,可以用CPTRectAnchor列舉型別,指定標題向圖框的4角、4邊(中點)對齊標題位置 預設值:CPTRectAnchorTop(頂部居中)
        graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
        // 標題對齊時的偏移距離(相對於titlePlotAreaFrameAnchor的偏移距離)預設值:CGPointZero
        graph.titleDisplacement = CGPointZero;
        // 標題文字樣式 預設值:nil
        CPTMutableTextStyle *textStyle = [[CPTMutableTextStyle alloc] init];
        textStyle.fontSize = CPTFloat(25);
        textStyle.textAlignment = CPTTextAlignmentLeft;
        graph.titleTextStyle = textStyle;
    }
    
    // CPGGraph內邊距,預設值:20.0f
    {
        graph.paddingLeft = CPTFloat(0);
        graph.paddingTop = CPTFloat(0);
        graph.paddingRight = CPTFloat(0);
        graph.paddingBottom = CPTFloat(0);
    }
    
    // CPTPlotAreaFrame繪圖區域設定
    {
        // 內邊距設定,預設值:0.0f
        graph.plotAreaFrame.paddingLeft = CPTFloat(0);
        graph.plotAreaFrame.paddingTop = CPTFloat(0);
        graph.plotAreaFrame.paddingRight = CPTFloat(0);
        graph.plotAreaFrame.paddingBottom = CPTFloat(0);
        // 邊框樣式設定 預設值:nil
        graph.plotAreaFrame.borderLineStyle=nil;
    }
}

CorePlot為CPTGraph提供了幾種主題可供使用,有:kCPTDarkGradientTheme、kCPTPlainBlackTheme、kCPTPlainWhiteTheme、kCPTSlateTheme、kCPTStocksTheme。每種可以切換主題試試有什麼不同的效果。內邊距(paddingLeft、paddingTop、paddingRight、paddingBottom)來自於父類CPTLayer。CPTLayer是CorePlot中所有層(Layer)的父類,繼承於CALayer。繪圖邊框(plotAreaFrame)中關聯了繪圖區域(CPTPlotArea)、座標系(CPTAxisSet)。

繪圖空間(CPTXYPlotSpace)的建立

CPTXYPlotSpace是CPTPlotSpace的子類。繪圖空間定義了座標空間和繪製空間的對映關係。CPTXYPlotSpace則定義了在二維(x、y軸)中的對映關係。

#pragma mark 建立繪圖空間
- (void)createPlotSpace
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)_hostView.hostedGraph.defaultPlotSpace;
    // 繪圖空間是否允許與使用者互動 預設值:NO
    plotSpace.allowsUserInteraction = YES;
    // 委託事件
    plotSpace.delegate = self;
    
    //設定移動時的停止動畫
    {
        // 這些引數保持預設即可  變化不大
        plotSpace.allowsMomentum = YES;
        plotSpace.momentumAnimationCurve = CPTAnimationCurveCubicIn;
        plotSpace.bounceAnimationCurve = CPTAnimationCurveBackIn;
        plotSpace.momentumAcceleration = 20000.0;
    }
    
    // 可顯示大小 一屏內橫軸/縱軸的顯示範圍
    {
        // 橫軸
        {
            // location表示座標的顯示起始值,length表示要顯示的長度 類似於NSRange
            CPTMutablePlotRange *xRange = [CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(-1) length:CPTDecimalFromCGFloat(_coordinatesX.count + 1)];
            // 橫軸顯示的收縮/擴大範圍 1:不改變  <1:收縮範圍  >1:擴大範圍
            [xRange expandRangeByFactor:CPTDecimalFromCGFloat(1)];
            
            plotSpace.xRange = xRange;
        }
        
        // 縱軸
        {
            CPTMutablePlotRange *yRange = [CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(-1) length:CPTDecimalFromCGFloat(11)];
            [yRange expandRangeByFactor:CPTDecimalFromCGFloat(1)];
            
            plotSpace.yRange = yRange;
        }
    }
    
    // 繪圖空間的最大顯示空間,滾動範圍
    {
        CPTMutablePlotRange *xGlobalRange = [CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(-2) length:CPTDecimalFromCGFloat(_coordinatesX.count + 5)];
        
        CPTMutablePlotRange *yGlobalRange = [CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(-2) length:CPTDecimalFromCGFloat(16)];
        
        plotSpace.globalXRange = xGlobalRange;
        plotSpace.globalYRange = yGlobalRange;
    }
}

需著重理解xRange/yRange於globalXRange/globalYRange之間的區別。xRange/yRange是指在檢視中顯示的範圍,人們可以看到的範圍。globalXRange/globalYRange是指繪圖空間最大顯示範圍(滾動範圍),可以通過手指拖動看到其他的範圍。xRange/yRange類似於UIScorllView中frame的size,globalXRange/globalYRange類似於UIScrollView中的contentSize。

CPTPlotSpace的委託事件

#pragma mark 替換移動座標
- (CGPoint)plotSpace:(CPTPlotSpace *)space willDisplaceBy:(CGPoint)proposedDisplacementVector
{
//    NSLog(@"\n============willDisplaceBy==========\n");
//    NSLog(@"原始的將要移動的座標:%@", NSStringFromCGPoint(proposedDisplacementVector));
//    
    return proposedDisplacementVector;
}

#pragma mark 是否允許縮放
- (BOOL)plotSpace:(CPTPlotSpace *)space shouldScaleBy:(CGFloat)interactionScale aboutPoint:(CGPoint)interactionPoint
{
//    NSLog(@"\n============shouldScaleBy==========\n");
//    NSLog(@"縮放比例:%lf", interactionScale);
//    NSLog(@"縮放的中心點:%@", NSStringFromCGPoint(interactionPoint));
    return YES;
}

#pragma mark 縮放繪圖空間時呼叫,設定當前顯示的大小
- (CPTPlotRange *)plotSpace:(CPTPlotSpace *)space willChangePlotRangeTo:(CPTPlotRange *)newRange forCoordinate:(CPTCoordinate)coordinate
{
//    NSLog(@"\n============willChangePlotRangeTo==========\n");
//    NSLog(@"座標型別:%d", coordinate);
//    // CPTPlotRange 有比較方法 containsRange:
//    NSLog(@"原始的座標空間:location:%@,length:%@", [NSDecimalNumber decimalNumberWithDecimal:newRange.location].stringValue, [NSDecimalNumber decimalNumberWithDecimal:newRange.length].stringValue);
//    
    return newRange;
}

#pragma mark 結束縮放繪圖空間時呼叫
- (void)plotSpace:(CPTPlotSpace *)space didChangePlotRangeForCoordinate:(CPTCoordinate)coordinate
{
//    NSLog(@"\n============didChangePlotRangeForCoordinate==========\n");
//    NSLog(@"座標型別:%d", coordinate);
}

#pragma mark 開始按下 point是在hostedGraph中的座標
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDownEvent:(CPTNativeEvent *)event atPoint:(CGPoint)point
{
    NSLog(@"\n\n\n============shouldHandlePointingDeviceDownEvent==========\n");
    NSLog(@"座標點:%@", NSStringFromCGPoint(point));
    
    return YES;
}

#pragma mark 開始拖動 point是在hostedGraph中的座標
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDraggedEvent:(CPTNativeEvent *)event atPoint:(CGPoint)point
{
    NSLog(@"\n\n\n============shouldHandlePointingDeviceDraggedEvent==========\n");
    NSLog(@"座標點:%@", NSStringFromCGPoint(point));
    
    return YES;
}

#pragma mark 鬆開 point是在hostedGraph中的座標
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceUpEvent:(CPTNativeEvent *)event atPoint:(CGPoint)point
{
    NSLog(@"\n\n\n============shouldHandlePointingDeviceUpEvent==========\n");
    NSLog(@"座標點:%@", NSStringFromCGPoint(point));
    
    return YES;
}

#pragma mark 取消,如:來電時產生的取消事件
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceCancelledEvent:(CPTNativeEvent *)event
{
    NSLog(@"\n\n\n============shouldHandlePointingDeviceCancelledEvent==========\n");
    
    return YES;
}

座標系(CPTXYAxisSet)的建立

CPTXYAxisSet繼承自CPTAxisSet,是一個二維座標(x軸、y軸)。

#pragma mark 建立座標
- (void)createAxis
{
    // 軸線樣式
    CPTMutableLineStyle *axisLineStyle = [[CPTMutableLineStyle alloc] init];
    axisLineStyle.lineWidth = CPTFloat(1);
    axisLineStyle.lineColor = [CPTColor blackColor];
    
    // 標題樣式
    CPTMutableTextStyle *titelStyle = [CPTMutableTextStyle textStyle];
    titelStyle.color = [CPTColor redColor];
    titelStyle.fontSize = CPTFloat(20);
    
    // 主刻度線樣式
    CPTMutableLineStyle *majorLineStyle = [CPTMutableLineStyle lineStyle];
    majorLineStyle.lineColor = [CPTColor purpleColor];
    
    // 細分刻度線樣式
    CPTMutableLineStyle *minorLineStyle = [CPTMutableLineStyle lineStyle];
    minorLineStyle.lineColor = [CPTColor blueColor];
    
    // 軸標籤樣式
    CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
    axisTextStyle.color = [CPTColor blueColor];
    axisTextStyle.fontName = @"Helvetica-Bold";
    axisTextStyle.fontSize = CPTFloat(11);
    
    // 軸標籤樣式
    CPTMutableTextStyle *axisLabelTextStyle = [[CPTMutableTextStyle alloc] init];
    axisLabelTextStyle.color=[CPTColor greenColor];
    axisLabelTextStyle.fontSize = CPTFloat(17);
    
    // 座標系
    CPTXYAxisSet *axis = (CPTXYAxisSet *)_hostView.hostedGraph.axisSet;
    
    //X軸設定
    {
        // 獲取X軸線
        CPTXYAxis *xAxis = axis.xAxis;
        
        // 軸線設定
        xAxis.axisLineStyle = axisLineStyle;
        
        // 顯示的刻度範圍 預設值:nil
        xAxis.visibleRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(_coordinatesX.count - 1)];
        
        // 標題設定
        {
            xAxis.title [email protected] "X軸";
            // 文字樣式
            xAxis.titleTextStyle = titelStyle;
            // 位置 與刻度有關,
            xAxis.titleLocation = CPTDecimalFromFloat(2);
            // 方向設定
            xAxis.titleDirection = CPTSignNegative;
            // 偏移量,在方向上的偏移量
            xAxis.titleOffset = CPTFloat(25);
        }
        
        // 位置設定
        {
            // 固定座標 預設值:nil
            //xAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:50.0];
            // 座標原點所在位置,預設值:CPTDecimalFromInteger(0)(在Y軸的0點位置)
            xAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0);
        }
        
        // 主刻度線設定
        {
            // X軸大刻度線,線型設定
            xAxis.majorTickLineStyle = majorLineStyle;
            // 刻度線的長度
            xAxis.majorTickLength = CPTFloat(5);
            // 刻度線位置
            NSMutableSet *majorTickLocations =[NSMutableSet setWithCapacity:_coordinatesX.count];
            for (int i= 0 ;i< _coordinatesX.count ;i++) {
                [majorTickLocations addObject:[NSNumber numberWithInt:(i)]];
            }
            xAxis.majorTickLocations = majorTickLocations;
        }
        
        // 細分刻度線設定
        {
            // 刻度線的長度
            xAxis.minorTickLength = CPTFloat(3);
            // 刻度線樣式
            xAxis.minorTickLineStyle = minorLineStyle;
            // 刻度線位置
            NSInteger minorTicksPerInterval = 3;
            CGFloat minorIntervalLength = CPTFloat(1) / CPTFloat(minorTicksPerInterval + 1);
            NSMutableSet *minorTickLocations =[NSMutableSet setWithCapacity:(_coordinatesX.count - 1) * minorTicksPerInterval];
            for (int i= 0 ;i< _coordinatesX.count - 1;i++) {
                for (int j = 0; j < minorTicksPerInterval; j++) {
                    [minorTickLocations addObject:[NSNumber numberWithFloat:(i + minorIntervalLength * (j + 1))]];
                }
            }
            xAxis.minorTickLocations = minorTickLocations;
        }
        
        // 網格線設定
        {
            //xAxis.majorGridLineStyle = majorLineStyle;
            //xAxis.minorGridLineStyle = minorLineStyle;
            //xAxis.gridLinesRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(9)];
        }
        
        // 軸標籤設定
        {
            //清除預設的方案,使用自定義的軸標籤、刻度線;
            xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
            // 軸標籤偏移量
            xAxis.labelOffset = 0.f;
            // 軸標籤樣式
            xAxis.labelTextStyle = axisTextStyle;
            
            // 存放自定義的軸標籤
            NSMutableSet *xAxisLabels = [NSMutableSet setWithCapacity:_coordinatesX.count];
            for ( int i= 0 ;i< _coordinatesX.count ;i++) {
                CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:_coordinatesX[i] textStyle:axisLabelTextStyle];
                // 刻度線的位置
                newLabel.tickLocation = CPTDecimalFromInt(i);
                newLabel.offset = xAxis.labelOffset + xAxis.majorTickLength;
                newLabel.rotation = M_PI_4;
                [xAxisLabels addObject :newLabel];
            }
            xAxis.axisLabels = xAxisLabels;
        }
    }
    
    //Y軸設定
    {
        // 獲取Y軸座標
        CPTXYAxis *yAxis = axis.yAxis;
        
        // 委託事件
        yAxis.delegate = self;
        
        //軸線樣式
        yAxis.axisLineStyle = axisLineStyle;
        
        //顯示的刻度
        yAxis.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat(9)];
        
        // 標題設定
        {
            yAxis.title = @"Y軸";
            // 文字樣式
            yAxis.titleTextStyle = titelStyle;
            // 位置 與刻度有關,
            yAxis.titleLocation = CPTDecimalFromFloat(2.4);
            // 方向設定
            yAxis.titleDirection = CPTSignNegative;
            // 偏移量,在方向上的偏移量
            yAxis.titleOffset = CPTFloat(18);
            // 旋轉方向
            yAxis.titleRotation = CPTFloat(M_PI_2);
        }
        
        // 位置設定
        {
            // 獲取X軸原點即0點的座標
            CPTXYAxis *xAxis = axis.xAxis;
            CGPoint zeroPoint = [xAxis viewPointForCoordinateDecimalNumber:CPTDecimalFromFloat(0)];
            
            // 固定座標 預設值:nil
            yAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:CPTFloat(zeroPoint.x)];
            
            // 座標原點所在位置,預設值:CPTDecimalFromInteger(0)(在X軸的0點位置)
            //yAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0);
        }
        
        // 主刻度線設定
        {
            // 顯示數字標籤的量度間隔
            yAxis.majorIntervalLength = CPTDecimalFromFloat(1);
            // 刻度線,線型設定
            yAxis.majorTickLineStyle = majorLineStyle;
            // 刻度線的長度
            yAxis.majorTickLength = 6;
        }
        
        // 細分刻度線設定
        {
            // 每一個主刻度範圍內顯示細分刻度的個數
            yAxis.minorTicksPerInterval = 5;
            // 刻度線的長度
            yAxis.minorTickLength = CPTFloat(3);
            // 刻度線,線型設定
            yAxis.minorTickLineStyle = minorLineStyle;
        }
        
        // 網格線設定 預設不顯示
        {
            //yAxis.majorGridLineStyle = majorLineStyle;
            //yAxis.minorGridLineStyle = minorLineStyle;
            //yAxis.gridLinesRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(_coordinatesY.count)];
        }
        
        // 軸標籤設定
        {
            // 軸標籤偏移量
            yAxis.labelOffset = CPTFloat(5);
            // 軸標籤樣式
            yAxis.labelTextStyle = axisTextStyle;
            
            // 排除不顯示的標籤
            NSArray *exclusionRanges = [NSArray arrayWithObjects:
                                        [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.99) length:CPTDecimalFromDouble(0.02)],
                                        [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(2.99) length:CPTDecimalFromDouble(0.02)],
                                        nil];
            yAxis.labelExclusionRanges = exclusionRanges;
            
            // 因為沒有清除預設的軸標籤(CPTAxisLabelingPolicyNone),如果想要自定義軸標籤,需實現委託方法
        }
    }
}

如果想自定義標籤及刻度,則需要清除預設的方案,設定屬性labelingPolicy為CPTAxisLabelingPolicyNone,預設的軸標籤有4種:CPTAxisLabelingPolicyLocationsProvided、CPTAxisLabelingPolicyFixedInterval、CPTAxisLabelingPolicyAutomatic、CPTAxisLabelingPolicyEqualDivisions。如果採用預設的方案,只是採用它的刻度線設定,想使用自定義的軸標籤,則需要實現軸標籤的委託事件。

#pragma mark 是否使用系統的軸標籤樣式 並可改變標籤樣式 可用於任何標籤方案(labelingPolicy)
- (BOOL)axis:(CPTAxis *)axis shouldUpdateAxisLabelsAtLocations:(NSSet *)locations
{
    // 返回NO,使用自定義,返回YES,使用系統的標籤
    return NO;
}

散點圖、折線圖、曲線圖、直方圖(CPTScatterPlot)的建立

CPTScatterPlot用於建立散點圖,繼承自CPTPlot。

#pragma mark 建立平面圖,折線圖
- (void)createPlots
{
    // 建立折線圖
    CPTScatterPlot *scatterPlot = [[CPTScatterPlot alloc] init];
    
    // 新增圖形到繪圖空間
    [_hostView.hostedGraph addPlot:scatterPlot];
    
    // 標識,根據此@ref identifier來區分不同的plot,也是圖例顯示名稱,
    scatterPlot.identifier = @"scatter";
    
    // 設定資料來源,需應用CPTScatterPlotDataSource協議
    scatterPlot.dataSource = self;
    
    // 委託事件
    scatterPlot.delegate = self;
    
    // 線性顯示方式設定 預設值:CPTScatterPlotInterpolationLinear(折線圖)
    // CPTScatterPlotInterpolationCurved(曲線圖)
    // CPTScatterPlotInterpolationStepped/CPTScatterPlotInterpolationHistogram(直方圖)
    scatterPlot.interpolation = CPTScatterPlotInterpolationCurved;
    
    // 資料標籤設定,如果想用自定義的標籤,則需要資料來源方法:dataLabelForPlot:recordIndex:
    {
        // 偏移量設定
        scatterPlot.labelOffset = 15;
        // 資料標籤樣式
        CPTMutableTextStyle *labelTextStyle = [[CPTMutableTextStyle alloc] init];
        labelTextStyle.color = [CPTColor magentaColor];
        scatterPlot.labelTextStyle = labelTextStyle;
    }
    
    // 線條樣式設定
    {
        CPTMutableLineStyle * scatterLineStyle = [[ CPTMutableLineStyle alloc ] init];
        scatterLineStyle.lineColor = [CPTColor blackColor];
        scatterLineStyle.lineWidth = 3;
        // 破折線
        scatterLineStyle.dashPattern = @[@(10.0),@(5.0)];
        
        // 如果設定為nil則為散點圖
        scatterPlot.dataLineStyle = scatterLineStyle;
    }
    
    // 新增拐點
    {
        // 符號型別:橢圓
        CPTPlotSymbol *plotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
        // 符號大小
        plotSymbol.size = CPTSizeMake(8.0f, 8.f);
        // 符號填充色
        plotSymbol.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
        // 邊框設定
        CPTMutableLineStyle *symboLineStyle = [[ CPTMutableLineStyle alloc ] init];
        symboLineStyle.lineColor = [CPTColor blackColor];
        symboLineStyle.lineWidth = 3;
        plotSymbol.lineStyle = symboLineStyle;
        
        // 向圖形上加入符號
        scatterPlot.plotSymbol = plotSymbol;
        
        // 設定拐點的外沿範圍,以用來擴大檢測手指的觸控範圍
        scatterPlot.plotSymbolMarginForHitDetection = CPTFloat(5);
        
    }
    
    // 建立漸變區
    {
        // 建立一個顏色漸變:從漸變色BeginningColor漸變到色endingColor
        CPTGradient *areaGradient = [CPTGradient gradientWithBeginningColor:[CPTColor blueColor] endingColor:[CPTColor clearColor]];
        // 漸變角度:-90 度(順時針旋轉)
        areaGradient.angle = -90.0f ;
        // 建立一個顏色填充:以顏色漸變進行填充
        CPTFill *areaGradientFill = [CPTFill fillWithGradient:areaGradient];
        // 為圖形設定漸變區
        scatterPlot.areaFill = areaGradientFill;
        // 漸變區起始值,小於這個值的圖形區域不再填充漸變色
        scatterPlot.areaBaseValue = CPTDecimalFromString (@"0.0" );
    }
    
    // 顯示動畫
    {
        scatterPlot.opacity = 0.0f;
        CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
        fadeInAnimation.duration            = 3.0f;
        fadeInAnimation.removedOnCompletion = NO;
        fadeInAnimation.fillMode            = kCAFillModeForwards;
        fadeInAnimation.toValue             = [NSNumber numberWithFloat:1.0];
        [scatterPlot addAnimation:fadeInAnimation forKey:@"animateOpacity"];
    }
}

在CPTXYScatterPlot中屬性interpolation用於設定線性顯示方式,它是一個列舉型別,有CPTScatterPlotInterpolationLinear(折線圖)、CPTScatterPlotInterpolationCurved(曲線圖)、CPTScatterPlotInterpolationSteppedCPTScatterPlotInterpolationHistogram(直方圖)4中,其中CPTScatterPlotInterpolationLinear是預設值。只要把線條樣式(dataLineStyle)的值設為nil,則是散點圖。

CPTScatterPlot的dataSource方法

#pragma mark 詢問有多少個數據
- (NSUInteger) numberOfRecordsForPlot:(CPTPlot *)plot {
    return self.dataSource.count;
}

#pragma mark 詢問一個個資料值 fieldEnum:一個軸型別,是一個列舉  idx:座標軸索引
- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
    NSNumber *num = nil;
    if(fieldEnum == CPTScatterPlotFieldY){            //詢問在Y軸上的值
        num = self.dataSource[idx];
    }else if (fieldEnum == CPTScatterPlotFieldX){     //詢問在X軸上的值
        num = @(idx);
    }
    return num;
}

#pragma mark 新增資料標籤,在拐點上顯示的文字
- (CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)idx
{
    // 資料標籤樣式
    CPTMutableTextStyle *labelTextStyle = [[CPTMutableTextStyle alloc] init];
    labelTextStyle.color = [CPTColor magentaColor];
    
    // 定義一個 TextLayer
    CPTTextLayer *newLayer = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:@"%d",[self.dataSource[idx] integerValue]] style:labelTextStyle];
    
    return newLayer;
}

CPTScatterPlot的delegate方法

#pragma mark 選擇拐點時
- (void)scatterPlot:(CPTScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)idx withEvent:(UIEvent *)event
{
    // 移除註釋
    CPTPlotArea *plotArea = _hostView.hostedGraph.plotAreaFrame.plotArea;
    [plotArea removeAllAnnotations];
    
    // 建立拐點註釋,plotSpace:繪圖空間 anchorPlotPoint:座標點
    CPTPlotSpaceAnnotation *symbolTextAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:_hostView.hostedGraph.defaultPlotSpace anchorPlotPoint:@[@(idx),self.dataSource[idx]]];
    
    // 文字樣式
    CPTMutableTextStyle *annotationTextStyle = [CPTMutableTextStyle textStyle];
    annotationTextStyle.color = [CPTColor greenColor];
    annotationTextStyle.fontSize = 17.0f;
    annotationTextStyle.fontName = @"Helvetica-Bold";
    // 顯示的字串
    NSString *randomValue = [NSString stringWithFormat:@"折線圖\n隨即值:%@ \n", [self.dataSource[idx] stringValue]];
    // 註釋內容
    CPTTextLayer *textLayer = [[CPTTextLayer alloc] initWithText:randomValue style:annotationTextStyle];
    // 添加註釋內容
    symbolTextAnnotation.contentLayer = textLayer;
    
    // 註釋位置
    symbolTextAnnotation.displacement = CGPointMake(CPTFloat(0), CPTFloat(20));
    
    // 把拐點註釋新增到繪圖區域中
    [plotArea addAnnotation:symbolTextAnnotation];
}

圖例(CPTLegend)的建立

#pragma mark 建立圖例
- (void)createLegend
{
    // 圖例樣式設定
    NSMutableArray *plots = [NSMutableArray array];
    for (int i = 0; i < _hostView.hostedGraph.allPlots.count; i++) {
        CPTScatterPlot *scatterPlot = _hostView.hostedGraph.allPlots[i];
        
        CPTScatterPlot *plot = [[CPTScatterPlot alloc] init];
        plot.dataLineStyle = scatterPlot.dataLineStyle;
        plot.plotSymbol = scatterPlot.plotSymbol;
        plot.identifier = @"折線圖";
        [plots addObject:plot];
    }
    // 圖例初始化
    CPTLegend *legend = [CPTLegend legendWithPlots:plots];
    // 圖例的列數。有時圖例太多,單列顯示太長,可分為多列顯示
    legend.numberOfColumns = 1;
    // 圖例外框的線條樣式
    legend.borderLineStyle = nil;
    // 圖例的填充屬性,CPTFill 型別
    legend.fill = [CPTFill fillWithColor:[CPTColor clearColor]];
    // 圖例中每個樣本的大小
    legend.swatchSize = CGSizeMake(40, 10);
    // 圖例中每個樣本的文字樣式
    CPTMutableTextStyle *titleTextStyle = [CPTMutableTextStyle textStyle];
    titleTextStyle.color = [CPTColor blackColor];
    titleTextStyle.fontName = @"Helvetica-Bold";
    titleTextStyle.fontSize = 13;
    legend.textStyle = titleTextStyle;
    
    // 把圖例於圖表關聯起來
    _hostView.hostedGraph.legend = legend;
    // 圖例對齊於圖框的位置,可以用 CPTRectAnchor 列舉型別,指定圖例向圖框的4角、4邊(中點)對齊,預設值:CPTRectAnchorBottom(底部居中)
    _hostView.hostedGraph.legendAnchor = CPTRectAnchorTopRight;
    // 圖例對齊時的偏移距離(相對於legendAnchor的偏移距離),預設值:CGPointZeor
    _hostView.hostedGraph.legendDisplacement = CGPointMake(-10, 0);
}
建立圖例時,如果圖例的名稱和CPTPlot屬性identifier的名稱一致,則不需要在單獨建立plots集合了,直接使用_hostView.hostedGraph.allPlots即可,因為土裡的圖示和名稱取得就是CPTScatterPlot的dataLineStyle、plotSymbol及identifier屬性。

相關推薦

CorePlot_1.5.1 繪製折線曲線圖直方圖

前言 CorePlot提供了散點圖(CPTScatterPlot)的繪製,包括:折線圖、曲線圖、直方圖。如下圖所示:      CorePlot框架自身提供了線條樣式、文字樣式及填充色的設定。CPTMutableLineStyle/CPTLineStyle用於設定線條樣式;

報表帆軟設計——巧用組合折線

只需要 原因 但是 最大值 可能 添加數據 變化 報表 如何使用 使用場景: 只需要折線圖,多個系列,每個系列的值差別很大(例如 系列1:0.08;系列2:8000),這樣的值不能使用同一個坐標軸(所以不能使用折線圖)。 如何使用:   1.新建一個自定義組合圖,加入有

MATLAB中scatter函式的用法繪製

標記輪廓顏色,指定為 'flat'、RGB 三元數或表中列出的顏色選項之一。預設值 'flat' 將使用 CData 屬性中的顏色。如果想自定義顏色,請指定一個 RGB 三元數。RGB 三元數是包含三個元素的行向量,其元素分別指定顏色中紅、綠、藍分量的強度。強度值必須位於 [0,1] 範圍內,例如 [0.4

JavaScript數據可視化編程學習Flotr2,包含簡單的,柱狀折線,餅

基礎 沒有 cat 勝利 而是 5.4 最好的 表數據 聯系 一、基礎柱狀圖 二、基礎的折線圖 三、基礎的餅圖 四、基礎的散點圖 一、基礎柱狀圖 如果你還沒有想好你的數據用什麽類型的圖表來展示你的數據,你應該首先考慮是否可以做成柱狀圖。柱狀圖可以表示數據的

python3使用matplotlib繪製,並標註圖例,軸

python3使用matplotlib繪製散點圖,並標註圖例,軸 程式碼 效果圖: 程式碼 from matplotlib import pyplot as plt from matplotlib import font_manager #

Python3機器學習實戰 kNN實現+matplotlib繪製

kNN.pyimport numpy as np # 運算子模組,這裡主要用來排序 import operator import matplotlib.pylab as plt def create_dataset(): group = np.array([[1.,

MATLAB繪製

scatter(X,Y,size,color)在向量X和Y的指定位置繪製彩色的圓圈。很顯然X與Y的大小是必須相同的。 load seamount scatter(x,y) 圖形如下 其中lo

2. matplotlib繪製

與繪製直線圖的唯一區別:plt.scatter # coding=utf-8 from matplotlib import pyplot as plt from matplotlib import font_manager my_font = font_manager.FontProperties(fna

python matplotlib從檔案中讀取資料繪製

示例說明:從一個檔案讀取資料,繪製成散點圖 #coding:utf-8 import matplotlib.pyplot as plt import numpy as np import matpl

scatter繪製

import numpy as np import matplotlib.pyplot as plt x = np.arange(1,10) y = x fig = plt.figure() ax1 = fig.add_subplot(11

Matlab R2017b 繪製

看論文時,我們經常看到的散點圖,既表達了資料的走勢,也顯示出了具體的資料點,是一種很好的資料處理方法。有的論文散點圖奇醜無比,沒有看下去的慾望;有的論文散點圖畫的簡單大方,一看就是行家呀。Matab 用plot可以畫圖,但是想自己DIY設定散點圖的引數,使用Matlab R2

scatter函式繪製——MATLAB

1、scatter(X,Y)在向量X和Y指定的位置顯示彩色圓; 如:scatter([1 2 3 4],[4 5 6 7]);效果如圖: 預設彩色圓為藍色空心圓 2、scatter(X,Y,S

R語言 繪製

[轉自:http://blog.sina.com.cn/s/blog_69ffa1f90101siek.html] 函式。簡單地說,把一些R語句(賦值、計算或其他操作步驟)包 裝起來並給它一個名稱,這就是函式。我們前面接觸過的 getClass( ), class( ), 

ggplot之繪製

1.處理散點重疊 geom_point(alpha=0.5) 2.向散點圖新增邊際地毯 geom_rug() 3.向散點圖新增標籤 geom_text(aes(y=informtality+0.2,label=Name)) 4.基於顏色和點型對資料分組 基於顏色

matlab實現畫一個x對應多個y

1、具體實現是,首選匯入資料 aray = importdata(’位置‘); [m,n] = size(array); 2、x軸間距設定 x = 1:1:m 3、處理陣列資料  figure(1)

python繪製並標記序號

實現二維平面上散點的繪製,並可以給每個散點標記序號或者名稱: import numpy as np import matplotlib.pyplot as plt x=[2.3,4.5,3,7,6.5,4,5.3] y=[5,4,7,5,5.3,5.5,6.2] n=np.

【01】使用TensorFlow繪製並顯示

1、使用TensorFlow繪製散點圖(程式碼)import tensorflow as tf import matplotlib.pyplot as plt # 隨機數生成 a = tf.random_normal([2,20]) # 啟動會話 sess = tf.Ses

ECharts系列:玩轉ECharts之常用折線柱狀餅狀關係

一.背景 最近產品叫我做一些集團系列的統計圖,包括集團組織、協作、銷售、採購等方面的。作為一名後端程式設計師,於是趁此機會來研究研究這個庫。 如果你僅僅停留在用的層面,那還是蠻簡單的。 二.介紹 ECharts,縮寫來自Enterprise Charts,商業級資料圖表,它最初是為了滿足公司商業體系裡各種業務

ArcGIS Enterprise 10.5.1 靜默安裝部署記錄Centos 7.2 minimal版- 2安裝Portal for ArcGIS

-a 切換 https stop user 安裝 執行 limits 方式 安裝Portal for ArcGIS 解壓portal安裝包,tar -xzvf Portal_for_ArcGIS_Linux_1051_156440.tar.gz 切換到arcgis賬戶靜

ArcGIS Enterprise 10.5.1 靜默安裝部署記錄Centos 7.2 minimal版- 3安裝 ArcGIS for Server

切換 驗證 裝包 start dap sof 訪問權限 tar 服務 安裝ArcGIS for Server 解壓server安裝包,tar -xzvf ArcGIS_Server_Linux_1051_156429.tar.gz 切換到arcgis賬戶靜默安裝serv