Core Plot-гистограмма со средней горизонтальной линией

есть ли способ добавить среднюю горизонтальную линию (или какую-либо одну линию) в гистограмму с помощью базовой структуры графика?

спасибо.

3 ответов


один из способов сделать это с помощью CPTScatterPlot:

добавьте следующие строки в свой код после инициализации и добавления гистограммы (или того, что когда-либо было вашим фактическим графиком данных) на график.

// Before following code, initialize your data, actual data plot and add plot to graph

CPTScatterPlot *dataSourceLinePlot = [[[CPTScatterPlot alloc] init] autorelease];
CPTMutableLineStyle * lineStyle                      = [CPTMutableLineStyle lineStyle];
lineStyle.lineWidth              = 3.f;
lineStyle.lineColor              = [CPTColor blackColor];
lineStyle.dashPattern            = [NSArray arrayWithObjects:[NSNumber numberWithFloat:3.0f], [NSNumber numberWithFloat:3.0f], nil];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.identifier    = @"horizontalLineForAverage";
dataSourceLinePlot.dataSource    = self;
[barChart addPlot:dataSourceLinePlot toPlotSpace:plotSpace];

затем добавьте методы источника данных, в моем случае я установил источник данных в вышеуказанном коде для себя, поэтому я определяю методы источника данных в том же файле:

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{   
// Note this method will return number of records for both my actual plot, and for scattered plot which is used to draw horizontal average line. For latter, this will decide the horizontal length of your line
    return [myDataArray count];
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    NSDecimalNumber *num = nil;

        // If method is called to fetch data about drawing horizontal average line, then return your generated average value.
    if( plot.identifier==@"horizontalLineForAverage")
    {
        if(fieldEnum == CPTScatterPlotFieldX )
        {
                    // this line will remain as it is
            num =(NSDecimalNumber *)[NSDecimalNumber numberWithDouble:index];
        }
        else
        {
            num = (NSDecimalNumber *) myDataAverageValue;// Here you generate average value for location of horizontal line. You should edit this line only;
        }
    }
// handle other cases and return data for other plots       
    return num;
}

да. Добавьте на график точечную диаграмму и дайте ей две точки данных-по одной на каждом конце нужной линии.


    CPTFill *bandFill = [CPTFill fillWithColor:[[CPTColor blackColor] colorWithAlphaComponent:1]];
    [y addBackgroundLimitBand:[CPTLimitBand limitBandWithRange:[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(800) length:CPTDecimalFromDouble(1.5)] fill:bandFill]];

и

-(CPTPlotRange *)plotSpace:(CPTPlotSpace *)space willChangePlotRangeTo:(CPTPlotRange *)newRange forCoordinate:(CPTCoordinate)coordinate
{
    if (self.segment.selectedSegmentIndex == 2) {
        if (coordinate == CPTCoordinateY) {

            //NSLog(@"%f=>%f",self.yRange.lengthDouble,newRange.lengthDouble);

            CPTGraph* graph = space.graph;
            CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
            CPTXYAxis *y = axisSet.yAxis;
            NSArray *bands = y.backgroundLimitBands;
            for (CPTLimitBand *band in bands) {
                [y removeBackgroundLimitBand:band];
            }

            CPTFill *bandFill = [CPTFill fillWithColor:[[CPTColor blackColor] colorWithAlphaComponent:1]];
            [y addBackgroundLimitBand:[CPTLimitBand limitBandWithRange:[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(800) length:CPTDecimalFromDouble(1.5 * newRange.lengthDouble / 1200)] fill:bandFill]];
        }

    }

    return newRange;

}

пожалуйста, обратитесь к разделу "AxisDemo" официального образца "Plot_Gallery_iOS"