Charts 折线图常用属性以及一些扩展

字数 403阅读 153

使用:

 _chartView =[[LineChartView alloc]initWithFrame:CGRectMake(10, 0, ScreenWidth -20, SCREEN_HEIGHT - 200)];
    [self.view addSubview:_chartView];
    _chartView.delegate = self;
    _chartView.chartDescription.enabled = NO;
    _chartView.dragEnabled = YES;
    [_chartView setScaleEnabled:NO];
    _chartView.pinchZoomEnabled = NO;
    _chartView.drawGridBackgroundEnabled = YES;

    _chartView.xAxis.gridLineDashLengths = @[@10.0, @10.0];
    _chartView.xAxis.gridLineDashPhase = 0.f;
    //Y轴设置
    ChartYAxis *leftAxis = _chartView.leftAxis;
    [leftAxis removeAllLimitLines];
    leftAxis.axisMaximum = 120.0; //最大值
    leftAxis.axisMinimum = -0.0; //最小值
    leftAxis.gridLineDashLengths = @[@5.f, @5.f];
    leftAxis.drawZeroLineEnabled = NO;
    leftAxis.drawLimitLinesBehindDataEnabled = YES;
    leftAxis.inverted = NO;//是否翻转
    //Y轴上数据格式
    leftAxis.valueFormatter = [[SymbolsValueFormatter alloc]init];
    leftAxis.labelPosition = YAxisLabelPositionOutsideChart;//label位置
    leftAxis.labelTextColor = [UIColor blackColor];//文字颜色
    leftAxis.labelFont = [UIFont systemFontOfSize:10.0f];//文字字体
    leftAxis.gridColor = [UIColor grayColor];//网格线颜色
    leftAxis.gridAntialiasEnabled = NO;//开启抗锯齿
    _chartView.rightAxis.enabled = NO;

    //X轴设置
    ChartXAxis *xAxis = _chartView.xAxis;
    xAxis.granularityEnabled = YES;//设置重复的值不显示
    xAxis.labelPosition= XAxisLabelPositionBottom;//设置x轴数据在底部
    xAxis.gridColor = [UIColor clearColor];
    xAxis.labelTextColor = [UIColor blackColor];//x轴上文字颜色
    xAxis.axisLineColor = [UIColor redColor];
    //X轴上数据格式
    xAxis.valueFormatter = [[DateValueFormatter alloc]init];

    _chartView.legend.form = ChartLegendFormLine;

    ChartViewPortHandler *scaleX = _chartView.viewPortHandler;

    [scaleX setMinimumScaleX:1.5f];//只滑动不缩放:(系统内部默认是先缩放后滑动)及初始化时x轴就缩放1.5倍,就可以滑动了,
    [_chartView animateWithXAxisDuration:2.5];

    [self setDataCount:20 range:100];
 //每一条线代表一条dataSet
    LineChartDataSet *set1 = nil;
    if (_chartView.data.dataSetCount > 0)
    {
        set1 = (LineChartDataSet *)_chartView.data.dataSets[0];
        [set1 replaceEntries: values];
        [_chartView.data notifyDataChanged];
        [_chartView notifyDataSetChanged];
    }
    else
    {
        //折线数据填充
        set1 = [[LineChartDataSet alloc] initWithEntries:values label:@"第一条折线"];
        set1.valueFormatter =[[SetValueFormatter alloc]initWithArr:values];
        set1.mode = LineChartModeCubicBezier;//平滑曲线
        set1.drawIconsEnabled = NO;
        set1.lineDashLengths = @[@5.f, @2.5f];
        set1.highlightLineDashLengths = @[@5.f, @2.5f];
        [set1 setColor:UIColor.blackColor];//线条颜色
        [set1 setCircleColor:UIColor.redColor];//圆圈的颜色
        set1.lineWidth = 1.0;
        set1.circleRadius = 8.0;
        set1.circleHoleRadius = 4;//小圆半径
        set1.circleHoleColor =  UIColor.blueColor;//小圆颜色
        set1.drawCircleHoleEnabled = YES;//是否绘制小圆
        set1.valueFont = [UIFont systemFontOfSize:9.f];//曲线上valulLabel的大小
        
        //最下方第一条折线的设置
        set1.formLineDashLengths = @[@5.f, @2.5f];
        set1.formLineWidth = 1.0;
        set1.formSize = 15.0;
        
        //渐变色设置
        NSArray *gradientColors = @[
                                    (id)[ChartColorTemplates colorFromString:@"#00ff0000"].CGColor,
                                    (id)[ChartColorTemplates colorFromString:@"#ffff0000"].CGColor
                                    ];
        CGGradientRef gradient = CGGradientCreateWithColors(nil, (CFArrayRef)gradientColors, nil);
        
        set1.fillAlpha = 1.0f;
        set1.fill = [ChartFill fillWithLinearGradient:gradient angle:90.f];
        set1.drawFilledEnabled = YES;
        CGGradientRelease(gradient);
        NSMutableArray *dataSets = [[NSMutableArray alloc] init];
        [dataSets addObject:set1];
        
        LineChartData *data = [[LineChartData alloc] initWithDataSets:dataSets];
        
        //赋予chartView数据
        _chartView.data = data;

注意点

x轴,y轴的数据自定义需要遵守协议:IChartAxisValueFormatter
折线上的数据自定义需要遵守协议:IChartValueFormatter

- (NSString *)stringForValue:(double)value axis:(ChartAxisBase *)axis
{
    return [NSString stringWithFormat:@"%.f月",value];
}

上面方法返回的value就是真实值

一些使用细节

WX20190926-165333@2x.png

如上图的需求,对charts做一些定制化,简单总结下属性:

X 轴:

如果需要记录x轴文字选中的属性,需要在高亮的方法中记录LineChartRenderer中记录highLightIndex

 open override func drawHighlighted(context: CGContext, indices: [Highlight])
    {
        guard
            let dataProvider = dataProvider,
            let lineData = dataProvider.lineData
            else { return }
        
        let chartXMax = dataProvider.chartXMax
        
        context.saveGState()
        
        for high in indices
        {
            guard let set = lineData.getDataSetByIndex(high.dataSetIndex) as? ILineChartDataSet
                , set.isHighlightEnabled
                else { continue }
            
            guard let e = set.entryForXValue(high.x, closestToY: high.y) else { continue }
            
            if !isInBoundsX(entry: e, dataSet: set)
            {
                continue
            }
        
            highLightIndex = e.x

在绘制的时候把高亮给x轴,BarLineChartViewBasedraw方法中:

  xAxisRenderer.highLightIndex = index

最后在XAxisRenderer类中 drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint)的方法中改动即可

if highLightIndex == i {
                 labelAttrs =  [
                    .font: xAxis.labelHighLightFont,
                    .foregroundColor: xAxis.labelHighLighhtTextColor,
                    .paragraphStyle: paraStyle
                ]
            }else{
                labelAttrs = [
                .font: xAxis.labelFont,
                .foregroundColor: xAxis.labelTextColor,
                .paragraphStyle: paraStyle
                ]
            }

Y 轴的一些常用设置:

如果需要定制Y轴的分段个数,必须用以下方法设置设置,这个方法里会重新设置forceLabelsEnabled

leftAxis setLabelCount:count force:YES];

如果需要定制Y轴文字显示的小数点,单位等等
可以继承NSNumberFormatter,遵守协议IChartAxisValueFormatter,实现方法:

//左侧Y轴单位
    ValueFormatter *yFormatter =[[ValueFormatter alloc]init];
        
        yFormatter.positiveSuffix = @"度";
    }
      设置小数点
        yFormatter.maximumFractionDigits = 2;
        yFormatter.minimumFractionDigits = 2;

    }
//返回y轴的数据
- (NSString *)stringForValue:(double)value axis:(ChartAxisBase *)axis
{
        return [self stringFromNumber:[NSNumber numberWithDouble:value]];
    }
    
}

如上图,需求是Y轴6条线,需要显示3个分段,我们可以这样处理:

//返回y轴的数据
- (NSString *)stringForValue:(double)value axis:(ChartAxisBase *)axis
{
    NSArray *array = axis.entries;
    NSInteger index = 0;
    for (NSNumber *obj in array) {
        if ([obj doubleValue] == value) {
            index = [array indexOfObject:obj];
            break;
        }
    }
    if (index % _ignoreCount == 0 && _ignoreCount != 0) {
        return @"";
    }else{
        return [self stringFromNumber:[NSNumber numberWithDouble:value]];
    }
    
}

折线的设置:
如果需要做选中的一些操作,必须打开,set.highlightEnabled = YES,否则高亮时没有的; 打开后,会出现十字线。十字线的启动属性:

//选中拐点,是否开启高亮效果(显示十字线)
            set.drawVerticalHighlightIndicatorEnabled = NO;
            set.drawHorizontalHighlightIndicatorEnabled = NO;

如果是多条折线,不同的折线代表的内容不同,必如一个是温度曲线,一个是水量曲线,那么就需要设置折线依赖属性:axisDependency

set.axisDependency = AxisDependencyLeft; //AxisDependencyRight 依赖左侧Y轴,依赖右侧Y轴

是否绘制曲线上的文字:

set.drawValuesEnabled = NO
圆.png

圆的副本.png

推荐阅读更多精彩内容