用 Charts 绘图表框架制作统计图
2016-10-10 16:50
316 查看
集成 Charts 框架:http://www.th7.cn/Program/IOS/201610/978760.shtml
还要另外集成 Masonry 框架
使用举例:
折线图:
饼状图:
雷达图:
柱状图:
还要另外集成 Masonry 框架
使用举例:
折线图:
@interface LineViewController ()<ChartViewDelegate> @property (nonatomic,strong) LineChartView *LineChartView; @property (nonatomic, strong) LineChartData *data; @end @implementation LineViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor colorWithRed:230/255.0f green:253/255.0f blue:253/255.0f alpha:1]; //title UILabel *title_label = [[UILabel alloc] init]; title_label.text = @"Line Chart"; title_label.font = [UIFont systemFontOfSize:45]; title_label.textColor = [UIColor brownColor]; title_label.textAlignment = NSTextAlignmentCenter; [self.view addSubview:title_label]; [title_label mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(260, 50)); make.centerX.equalTo(self.view.mas_centerX); make.centerY.equalTo(self.view.mas_centerY).offset(-200); }]; //updateData btn UIButton *display_btn = [[UIButton alloc] init]; [display_btn setTitle:@"updateData" forState:UIControlStateNormal]; [display_btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; display_btn.titleLabel.textAlignment = NSTextAlignmentCenter; [self.view addSubview:display_btn]; [display_btn mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(200, 50)); make.centerX.equalTo(self.view.mas_centerX); make.centerY.equalTo(self.view.mas_centerY).offset(240); }]; [display_btn addTarget:self action:@selector(updateData) forControlEvents:UIControlEventTouchUpInside]; //添加LineChartView self.LineChartView = [[LineChartView alloc] init]; self.LineChartView.delegate = self;//设置代理 [self.view addSubview:self.LineChartView]; [self.LineChartView mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(self.view.bounds.size.width-20, 300)); make.center.mas_equalTo(self.view); }]; //基本样式 self.LineChartView.backgroundColor = [UIColor colorWithRed:230/255.0f green:253/255.0f blue:253/255.0f alpha:1]; self.LineChartView.noDataText = @"暂无数据"; //交互样式 self.LineChartView.scaleYEnabled = NO;//取消Y轴缩放 self.LineChartView.doubleTapToZoomEnabled = NO;//取消双击缩放 self.LineChartView.dragEnabled = YES;//启用拖拽图标 self.LineChartView.dragDecelerationEnabled = YES;//拖拽后是否有惯性效果 self.LineChartView.dragDecelerationFrictionCoef = 0.9;//拖拽后惯性效果的摩擦系数(0~1),数值越小,惯性越不明显 //X轴样式 ChartXAxis *xAxis = self.LineChartView.xAxis; xAxis.axisLineWidth = 1.0/[UIScreen mainScreen].scale;//设置X轴线宽 xAxis.labelPosition = XAxisLabelPositionBottom;//X轴的显示位置,默认是显示在上面的 xAxis.drawGridLinesEnabled = NO;//不绘制网格线 xAxis.spaceBetweenLabels = 4;//设置label间隔 xAxis.labelTextColor = [self colorWithHexString:@"#057748"];//label文字颜色 //Y轴样式 self.LineChartView.rightAxis.enabled = NO;//不绘制右边轴 ChartYAxis *leftAxis = self.LineChartView.leftAxis;//获取左边Y轴 leftAxis.labelCount = 5;//Y轴label数量,数值不一定,如果forceLabelsEnabled等于YES, 则强制绘制制定数量的label, 但是可能不平均 leftAxis.forceLabelsEnabled = NO;//不强制绘制指定数量的label leftAxis.showOnlyMinMaxEnabled = NO;//是否只显示最大值和最小值 leftAxis.axisMinValue = 0;//设置Y轴的最小值 leftAxis.startAtZeroEnabled = YES;//从0开始绘制 leftAxis.axisMaxValue = 105;//设置Y轴的最大值 leftAxis.inverted = NO;//是否将Y轴进行上下翻转 leftAxis.axisLineWidth = 1.0/[UIScreen mainScreen].scale;//Y轴线宽 leftAxis.axisLineColor = [UIColor blackColor];//Y轴颜色 leftAxis.valueFormatter = [[NSNumberFormatter alloc] init];//自定义格式 leftAxis.valueFormatter.positiveSuffix = @" $";//数字后缀单位 leftAxis.labelPosition = YAxisLabelPositionOutsideChart;//label位置 leftAxis.labelTextColor = [self colorWithHexString:@"#057748"];//文字颜色 leftAxis.labelFont = [UIFont systemFontOfSize:10.0f];//文字字体 //网格线样式 leftAxis.gridLineDashLengths = @[@3.0f, @3.0f];//设置虚线样式的网格线 leftAxis.gridColor = [UIColor colorWithRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1];//网格线颜色 leftAxis.gridAntialiasEnabled = YES;//开启抗锯齿 //添加限制线 ChartLimitLine *limitLine = [[ChartLimitLine alloc] initWithLimit:80 label:@"限制线"]; limitLine.lineWidth = 2; limitLine.lineColor = [UIColor greenColor]; limitLine.lineDashLengths = @[@5.0f, @5.0f];//虚线样式 limitLine.labelPosition = ChartLimitLabelPositionRightTop;//位置 limitLine.valueTextColor = [self colorWithHexString:@"#057748"];//label文字颜色 limitLine.valueFont = [UIFont systemFontOfSize:12];//label字体 [leftAxis addLimitLine:limitLine];//添加到Y轴上 leftAxis.drawLimitLinesBehindDataEnabled = YES;//设置限制线绘制在折线图的后面 //描述及图例样式 [self.LineChartView setDescriptionText:@"折线图"]; [self.LineChartView setDescriptionTextColor:[UIColor darkGrayColor]]; self.LineChartView.legend.form = ChartLegendFormLine; self.LineChartView.legend.formSize = 30; self.LineChartView.legend.textColor = [UIColor darkGrayColor]; self.data = [self setData]; self.LineChartView.data = self.data; [self.LineChartView animateWithXAxisDuration:1.0f]; } -(void)updateData{ self.data = [self setData]; self.LineChartView.data = self.data; [self.LineChartView animateWithXAxisDuration:2.0f]; } //为折线图设置数据 - (LineChartData *)setData{ int xVals_count = 12;//X轴上要显示多少条数据 double maxYVal = 100;//Y轴的最大值 //X轴上面需要显示的数据 NSMutableArray *xVals = [[NSMutableArray alloc] init]; for (int i = 0; i < xVals_count; i++) { [xVals addObject:[NSString stringWithFormat:@"%d月", i+1]]; } //对应Y轴上面需要显示的数据 NSMutableArray *yVals = [[NSMutableArray alloc] init]; for (int i = 0; i < xVals_count; i++) { double mult = maxYVal + 1; double val = (double)(arc4random_uniform(mult)); ChartDataEntry *entry = [[ChartDataEntry alloc] initWithValue:val xIndex:i]; [yVals addObject:entry]; } LineChartDataSet *set1 = nil; if (self.LineChartView.data.dataSetCount > 0) { LineChartData *data = (LineChartData *)self.LineChartView.data; set1 = (LineChartDataSet *)data.dataSets[0]; set1.yVals = yVals; return data; }else{ //创建LineChartDataSet对象 set1 = [[LineChartDataSet alloc] initWithYVals:yVals label:@"lineName"]; //设置折线的样式 set1.lineWidth = 1.0/[UIScreen mainScreen].scale;//折线宽度 set1.drawValuesEnabled = YES;//是否在拐点处显示数据 set1.valueColors = @[[UIColor brownColor]];//折线拐点处显示数据的颜色 [set1 setColor:[self colorWithHexString:@"#007FFF"]];//折线颜色 set1.drawSteppedEnabled = NO;//是否开启绘制阶梯样式的折线图 //折线拐点样式 set1.drawCirclesEnabled = NO;//是否绘制拐点 set1.circleRadius = 4.0f;//拐点半径 set1.circleColors = @[[UIColor redColor], [UIColor greenColor]];//拐点颜色 //拐点中间的空心样式 set1.drawCircleHoleEnabled = YES;//是否绘制中间的空心 set1.circleHoleRadius = 2.0f;//空心的半径 set1.circleHoleColor = [UIColor blackColor];//空心的颜色 //折线的颜色填充样式 //第一种填充样式:单色填充 // set1.drawFilledEnabled = YES;//是否填充颜色 // set1.fillColor = [UIColor redColor];//填充颜色 // set1.fillAlpha = 0.3;//填充颜色的透明度 //第二种填充样式:渐变填充 set1.drawFilledEnabled = YES;//是否填充颜色 NSArray *gradientColors = @[(id)[ChartColorTemplates colorFromString:@"#FFFFFFFF"].CGColor, (id)[ChartColorTemplates colorFromString:@"#FF007FFF"].CGColor]; CGGradientRef gradientRef = CGGradientCreateWithColors(nil, (CFArrayRef)gradientColors, nil); set1.fillAlpha = 0.3f;//透明度 set1.fill = [ChartFill fillWithLinearGradient:gradientRef angle:90.0f];//赋值填充颜色对象 CGGradientRelease(gradientRef);//释放gradientRef //点击选中拐点的交互样式 set1.highlightEnabled = YES;//选中拐点,是否开启高亮效果(显示十字线) set1.highlightColor = [self colorWithHexString:@"#c83c23"];//点击选中拐点的十字线的颜色 set1.highlightLineWidth = 1.0/[UIScreen mainScreen].scale;//十字线宽度 set1.highlightLineDashLengths = @[@5, @5];//十字线的虚线样式 //将 LineChartDataSet 对象放入数组中 NSMutableArray *dataSets = [[NSMutableArray alloc] init]; [dataSets addObject:set1]; //添加第二个LineChartDataSet对象 // LineChartDataSet *set2 = [set1 copy]; // NSMutableArray *yVals2 = [[NSMutableArray alloc] init]; // for (int i = 0; i < xVals_count; i++) { // double mult = maxYVal + 1; // double val = (double)(arc4random_uniform(mult)); // ChartDataEntry *entry = [[ChartDataEntry alloc] initWithValue:val xIndex:i]; // [yVals2 addObject:entry]; // } // set2.yVals = yVals2; // [set2 setColor:[UIColor redColor]]; // set2.drawFilledEnabled = YES;//是否填充颜色 // set2.fillColor = [UIColor redColor];//填充颜色 // set2.fillAlpha = 0.1;//填充颜色的透明度 // [dataSets addObject:set2]; //创建 LineChartData 对象, 此对象就是lineChartView需要最终数据对象 LineChartData *data = [[LineChartData alloc] initWithXVals:xVals dataSets:dataSets]; [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:8.f]];//文字字体 [data setValueTextColor:[UIColor grayColor]];//文字颜色 NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; //自定义数据显示格式 [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; [formatter setPositiveFormat:@"#0.0"]; [data setValueFormatter:formatter]; return data; } } #pragma mark - ChartViewDelegate //点击选中折线拐点时回调 - (void)chartValueSelected:(ChartViewBase * _Nonnull)chartView entry:(ChartDataEntry * _Nonnull)entry dataSetIndex:(NSInteger)dataSetIndex highlight:(ChartHighlight * _Nonnull)highlight{ NSLog(@"---chartValueSelected---value: %g", entry.value); } //没有选中折线拐点时回调 - (void)chartValueNothingSelected:(ChartViewBase * _Nonnull)chartView{ NSLog(@"---chartValueNothingSelected---"); } //放大折线图时回调 - (void)chartScaled:(ChartViewBase * _Nonnull)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY{ NSLog(@"---chartScaled---scaleX:%g, scaleY:%g", scaleX, scaleY); } //拖拽折线图时回调 - (void)chartTranslated:(ChartViewBase * _Nonnull)chartView dX:(CGFloat)dX dY:(CGFloat)dY{ NSLog(@"---chartTranslated---dX:%g, dY:%g", dX, dY); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //将十六进制颜色转换为 UIColor 对象 - (UIColor *)colorWithHexString:(NSString *)color{ NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString]; // String should be 6 or 8 characters if ([cString length] < 6) { return [UIColor clearColor]; } // strip "0X" or "#" if it appears if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2]; if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1]; if ([cString length] != 6) return [UIColor clearColor]; // Separate into r, g, b substrings NSRange range; range.location = 0; range.length = 2; //r NSString *rString = [cString substringWithRange:range]; //g range.location = 2; NSString *gString = [cString substringWithRange:range]; //b range.location = 4; NSString *bString = [cString substringWithRange:range]; // Scan values unsigned int r, g, b; [[NSScanner scannerWithString:rString] scanHexInt:&r]; [[NSScanner scannerWithString:gString] scanHexInt:&g]; [[NSScanner scannerWithString:bString] scanHexInt:&b]; return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f]; } @end
饼状图:
#define BgColor [UIColor colorWithRed:230/255.0f green:253/255.0f blue:253/255.0f alpha:1] @interface PieViewController () @property (nonatomic, strong) PieChartView *pieChartView; @property (nonatomic, strong) PieChartData *data; @end @implementation PieViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = BgColor; //title UILabel *title_label = [[UILabel alloc] init]; title_label.text = @"饼状图"; title_label.font = [UIFont systemFontOfSize:45]; title_label.textColor = [UIColor brownColor]; title_label.textAlignment = NSTextAlignmentCenter; [self.view addSubview:title_label]; [title_label mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(260, 50)); make.centerX.equalTo(self.view.mas_centerX); make.centerY.equalTo(self.view.mas_centerY).offset(-200); }]; //updateData btn UIButton *display_btn = [[UIButton alloc] init]; [display_btn setTitle:@"updateData" forState:UIControlStateNormal]; [display_btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; display_btn.titleLabel.textAlignment = NSTextAlignmentCenter; [self.view addSubview:display_btn]; [display_btn mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(200, 50)); make.centerX.equalTo(self.view.mas_centerX); make.centerY.equalTo(self.view.mas_centerY).offset(240); }]; [display_btn addTarget:self action:@selector(updateData) forControlEvents:UIControlEventTouchUpInside]; //创建饼状图 self.pieChartView = [[PieChartView alloc] init]; self.pieChartView.backgroundColor = BgColor; [self.view addSubview:self.pieChartView]; [self.pieChartView mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(300, 300)); make.center.mas_equalTo(self.view); }]; //基本样式 [self.pieChartView setExtraOffsetsWithLeft:15 top:0 right:15 bottom:0];//饼状图距离边缘的间隙 self.pieChartView.usePercentValuesEnabled = YES;//是否根据所提供的数据, 将显示数据转换为百分比格式 self.pieChartView.dragDecelerationEnabled = YES;//拖拽饼状图后是否有惯性效果 self.pieChartView.drawSliceTextEnabled = YES;//是否显示区块文本 //空心饼状图样式 self.pieChartView.drawHoleEnabled = NO;//饼状图是否是空心 self.pieChartView.holeRadiusPercent = 0.5;//空心半径占比 self.pieChartView.holeColor = [UIColor clearColor];//空心颜色 self.pieChartView.transparentCircleRadiusPercent = 0.52;//半透明空心半径占比 self.pieChartView.transparentCircleColor = [UIColor colorWithRed:210/255.0 green:145/255.0 blue:165/255.0 alpha:0.3];//半透明空心的颜色 //实心饼状图样式 // self.pieChartView.drawHoleEnabled = NO; //饼状图中间描述 if (self.pieChartView.isDrawHoleEnabled == YES) { self.pieChartView.drawCenterTextEnabled = YES;//是否显示中间文字 //普通文本 // self.pieChartView.centerText = @"饼状图";//中间文字 //富文本 NSMutableAttributedString *centerText = [[NSMutableAttributedString alloc] initWithString:@"饼状图"]; [centerText setAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:16], NSForegroundColorAttributeName: [UIColor orangeColor]} range:NSMakeRange(0, centerText.length)]; self.pieChartView.centerAttributedText = centerText; } //饼状图描述 self.pieChartView.descriptionText = @"我是一个饼状图描述文字"; self.pieChartView.descriptionFont = [UIFont systemFontOfSize:10]; self.pieChartView.descriptionTextColor = [UIColor grayColor]; //饼状图图例 self.pieChartView.legend.maxSizePercent = 1;//图例在饼状图中的大小占比, 这会影响图例的宽高 self.pieChartView.legend.formToTextSpace = 5;//文本间隔 self.pieChartView.legend.font = [UIFont systemFontOfSize:10];//字体大小 self.pieChartView.legend.textColor = [UIColor grayColor];//字体颜色 self.pieChartView.legend.position = ChartLegendPositionBelowChartCenter;//图例在饼状图中的位置 self.pieChartView.legend.form = ChartLegendFormSquare;//图示样式: 方形、线条、圆形 self.pieChartView.legend.formSize = 12;//图示大小 //为饼状图提供数据 self.data = [self setData]; self.pieChartView.data = self.data; //设置动画效果 [self.pieChartView animateWithXAxisDuration:1.0f easingOption:ChartEasingOptionEaseOutExpo]; } - (void)updateData{ //为饼状图提供数据 self.data = [self setData]; self.pieChartView.data = self.data; //设置动画效果 [self.pieChartView animateWithXAxisDuration:1.0f easingOption:ChartEasingOptionEaseOutExpo]; } - (PieChartData *)setData{ double mult = 100; int count = 5;//饼状图总共有几块组成 //每个区块的数据 NSMutableArray *yVals = [[NSMutableArray alloc] init]; for (int i = 0; i < count; i++) { double randomVal = arc4random_uniform(mult + 1); BarChartDataEntry *entry = [[BarChartDataEntry alloc] initWithValue:randomVal xIndex:i]; [yVals addObject:entry]; } //每个区块的名称或描述 NSMutableArray *xVals = [[NSMutableArray alloc] init]; for (int i = 0; i < count; i++) { NSString *title = [NSString stringWithFormat:@"part%d", i+1]; [xVals addObject:title]; } //dataSet PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithYVals:yVals label:@""]; dataSet.drawValuesEnabled = YES;//是否绘制显示数据 NSMutableArray *colors = [[NSMutableArray alloc] init]; [colors addObjectsFromArray:ChartColorTemplates.vordiplom]; [colors addObjectsFromArray:ChartColorTemplates.joyful]; [colors addObjectsFromArray:ChartColorTemplates.colorful]; [colors addObjectsFromArray:ChartColorTemplates.liberty]; [colors addObjectsFromArray:ChartColorTemplates.pastel]; [colors addObject:[UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f]]; dataSet.colors = colors;//区块颜色 dataSet.sliceSpace = 3;//相邻区块之间的间距 dataSet.selectionShift = 8;//选中区块时, 放大的半径 dataSet.xValuePosition = PieChartValuePositionInsideSlice;//名称位置 dataSet.yValuePosition = PieChartValuePositionOutsideSlice;//数据位置 //数据与区块之间的用于指示的折线样式 dataSet.valueLinePart1OffsetPercentage = 0.85;//折线中第一段起始位置相对于区块的偏移量, 数值越大, 折线距离区块越远 dataSet.valueLinePart1Length = 0.5;//折线中第一段长度占比 dataSet.valueLinePart2Length = 0.4;//折线中第二段长度最大占比 dataSet.valueLineWidth = 1;//折线的粗细 dataSet.valueLineColor = [UIColor brownColor];//折线颜色 //data PieChartData *data = [[PieChartData alloc] initWithXVals:xVals dataSet:dataSet]; NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; formatter.numberStyle = NSNumberFormatterPercentStyle; formatter.maximumFractionDigits = 0;//小数位数 formatter.multiplier = @1.f; [data setValueFormatter:formatter];//设置显示数据格式 [data setValueTextColor:[UIColor brownColor]]; [data setValueFont:[UIFont systemFontOfSize:10]]; return data; } @end
雷达图:
#define BgColor [UIColor colorWithRed:230/255.0f green:253/255.0f blue:253/255.0f alpha:1] @interface RadarViewController ()<ChartViewDelegate> @property (nonatomic, strong) RadarChartView *radarChartView; @property (nonatomic, strong) RadarChartData *data; @end @implementation RadarViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = BgColor; //title UILabel *title_label = [[UILabel alloc] init]; title_label.text = @"Radar Chart"; title_label.font = [UIFont systemFontOfSize:45]; title_label.textColor = [UIColor brownColor]; title_label.textAlignment = NSTextAlignmentCenter; [self.view addSubview:title_label]; [title_label mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(260, 50)); make.centerX.equalTo(self.view.mas_centerX); make.centerY.equalTo(self.view.mas_centerY).offset(-200); }]; //updateData btn UIButton *display_btn = [[UIButton alloc] init]; [display_btn setTitle:@"updateData" forState:UIControlStateNormal]; [display_btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; display_btn.titleLabel.textAlignment = NSTextAlignmentCenter; [self.view addSubview:display_btn]; [display_btn mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(200, 50)); make.centerX.equalTo(self.view.mas_centerX); make.centerY.equalTo(self.view.mas_centerY).offset(240); }]; [display_btn addTarget:self action:@selector(updateData) forControlEvents:UIControlEventTouchUpInside]; //创建雷达图对象 self.radarChartView = [[RadarChartView alloc] init]; self.radarChartView.backgroundColor = BgColor; [self.view addSubview:self.radarChartView]; [self.radarChartView mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(300, 300)); make.center.mas_equalTo(self.view); }]; self.radarChartView.delegate = self; self.radarChartView.descriptionText = @"";//描述 self.radarChartView.rotationEnabled = YES;//是否允许转动 self.radarChartView.highlightPerTapEnabled = YES;//是否能被选中 //雷达图线条样式 self.radarChartView.webLineWidth = 0.5;//主干线线宽 self.radarChartView.webColor = [self colorWithHexString:@"#c2ccd0"];//主干线线宽 self.radarChartView.innerWebLineWidth = 0.375;//边线宽度 self.radarChartView.innerWebColor = [self colorWithHexString:@"#c2ccd0"];//边线颜色 self.radarChartView.webAlpha = 1;//透明度 //设置 xAxi ChartXAxis *xAxis = self.radarChartView.xAxis; xAxis.labelFont = [UIFont systemFontOfSize:15];//字体 xAxis.labelTextColor = [self colorWithHexString:@"#057748"];//颜色 //设置 yAxis ChartYAxis *yAxis = self.radarChartView.yAxis; yAxis.axisMinValue = 0.0;//最小值 yAxis.axisMaxValue = 150.0;//最大值 yAxis.drawLabelsEnabled = NO;//是否显示 label yAxis.labelCount = 6;// label 个数 yAxis.labelFont = [UIFont systemFontOfSize:9];// label 字体 yAxis.labelTextColor = [UIColor lightGrayColor];// label 颜色 //为雷达图提供数据 self.data = [self setData]; self.radarChartView.data = self.data; [self.radarChartView renderer]; //设置动画 [self.radarChartView animateWithYAxisDuration:0.1f]; } //刷新数据 - (void)updateData{ self.data = [self setData]; self.radarChartView.data = self.data; [self.radarChartView animateWithYAxisDuration:0.1f]; } //创建数据 - (RadarChartData *)setData{ double mult = 100; int count = 12;//维度的个数 //每个维度的名称或描述 NSMutableArray *xVals = [[NSMutableArray alloc] init]; for (int i = 0; i < count; i++) { [xVals addObject:[NSString stringWithFormat:@"%d 月", i+1]]; } //每个维度的数据 NSMutableArray *yVals1 = [[NSMutableArray alloc] init]; for (int i = 0; i < count; i++) { double randomVal = arc4random_uniform(mult) + mult / 2;//产生 50~150 的随机数 ChartDataEntry *entry = [[ChartDataEntry alloc] initWithValue:randomVal xIndex:i]; [yVals1 addObject:entry]; } RadarChartDataSet *set1 = [[RadarChartDataSet alloc] initWithYVals:yVals1 label:@"set 1"]; set1.lineWidth = 0.5;//数据折线线宽 [set1 setColor:[self colorWithHexString:@"#ff8936"]];//数据折线颜色 set1.drawFilledEnabled = YES;//是否填充颜色 set1.fillColor = [self colorWithHexString:@"#ff8936"];//填充颜色 set1.fillAlpha = 0.25;//填充透明度 set1.drawValuesEnabled = NO;//是否绘制显示数据 set1.valueFont = [UIFont systemFontOfSize:9];//字体 set1.valueTextColor = [UIColor grayColor];//颜色 // NSMutableArray *yVals2 = [[NSMutableArray alloc] init]; // for (int i = 0; i < count; i++) { // double randomVal = arc4random_uniform(mult) + mult / 2;//产生 50~150 的随机数 // ChartDataEntry *entry = [[ChartDataEntry alloc] initWithValue:randomVal xIndex:i]; // [yVals2 addObject:entry]; // } // RadarChartDataSet *set2 = [[RadarChartDataSet alloc] initWithYVals:yVals2 label:@"set 2"]; // set2.lineWidth = 0.5;//数据折线线宽 // set2.drawFilledEnabled = YES;//是否填充颜色 // [set2 setColor:[self colorWithHexString:@"#ff2d51"]]; // set2.fillColor = [self colorWithHexString:@"#ff2d51"]; // set2.fillAlpha = 0.25;//填充透明度 // set2.drawValuesEnabled = NO;//是否绘制显示数据 // set2.valueFont = [UIFont systemFontOfSize:9];//字体 // set2.valueTextColor = [UIColor grayColor];//颜色 RadarChartData *data = [[RadarChartData alloc] initWithXVals:xVals dataSets:@[set1]]; return data; } - (void)chartValueSelected:(ChartViewBase * _Nonnull)chartView entry:(ChartDataEntry * _Nonnull)entry dataSetIndex:(NSInteger)dataSetIndex highlight:(ChartHighlight * _Nonnull)highlight{ NSLog(@"chartValueSelected"); } - (void)chartValueNothingSelected:(ChartViewBase * _Nonnull)chartView{ NSLog(@"chartValueNothingSelected"); } - (void)chartScaled:(ChartViewBase * _Nonnull)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY{ NSLog(@"chartScaled"); } - (void)chartTranslated:(ChartViewBase * _Nonnull)chartView dX:(CGFloat)dX dY:(CGFloat)dY{ NSLog(@"chartTranslated"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //将十六进制颜色转换为 UIColor 对象 - (UIColor *)colorWithHexString:(NSString *)color{ NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString]; // String should be 6 or 8 characters if ([cString length] < 6) { return [UIColor clearColor]; } // strip "0X" or "#" if it appears if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2]; if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1]; if ([cString length] != 6) return [UIColor clearColor]; // Separate into r, g, b substrings NSRange range; range.location = 0; range.length = 2; //r NSString *rString = [cString substringWithRange:range]; //g range.location = 2; NSString *gString = [cString substringWithRange:range]; //b range.location = 4; NSString *bString = [cString substringWithRange:range]; // Scan values unsigned int r, g, b; [[NSScanner scannerWithString:rString] scanHexInt:&r]; [[NSScanner scannerWithString:gString] scanHexInt:&g]; [[NSScanner scannerWithString:bString] scanHexInt:&b]; return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f]; } @end
柱状图:
@interface BarViewController ()<ChartViewDelegate> @property (nonatomic, strong) BarChartView *barChartView; @property (nonatomic, strong) BarChartData *data; @end @implementation BarViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = [UIColor colorWithRed:230/255.0f green:253/255.0f blue:253/255.0f alpha:1]; //title UILabel *title_label = [[UILabel alloc] init]; title_label.text = @"Bar Chart"; title_label.font = [UIFont systemFontOfSize:45]; title_label.textColor = [UIColor brownColor]; title_label.textAlignment = NSTextAlignmentCenter; [self.view addSubview:title_label]; [title_label mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(200, 50)); make.centerX.equalTo(self.view.mas_centerX); make.centerY.equalTo(self.view.mas_centerY).offset(-200); }]; //updateData btn UIButton *display_btn = [[UIButton alloc] init]; [display_btn setTitle:@"updateData" forState:UIControlStateNormal]; [display_btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; display_btn.titleLabel.textAlignment = NSTextAlignmentCenter; [self.view addSubview:display_btn]; [display_btn mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(200, 50)); make.centerX.equalTo(self.view.mas_centerX); make.centerY.equalTo(self.view.mas_centerY).offset(240); }]; [display_btn addTarget:self action:@selector(updateData) forControlEvents:UIControlEventTouchUpInside]; //添加barChartView self.barChartView = [[BarChartView alloc] init]; self.barChartView.delegate = self;//设置代理 [self.view addSubview:self.barChartView]; [self.barChartView mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(self.view.bounds.size.width-20, 300)); make.center.mas_equalTo(self.view); }]; //基本样式 self.barChartView.backgroundColor = [UIColor colorWithRed:230/255.0f green:253/255.0f blue:253/255.0f alpha:1]; self.barChartView.noDataText = @"暂无数据";//没有数据时的文字提示 self.barChartView.drawValueAboveBarEnabled = YES;//数值显示在柱形的上面还是下面 self.barChartView.drawHighlightArrowEnabled = NO;//点击柱形图是否显示箭头 self.barChartView.drawBarShadowEnabled = NO;//是否绘制柱形的阴影背景 //交互设置 self.barChartView.scaleYEnabled = NO;//取消Y轴缩放 self.barChartView.doubleTapToZoomEnabled = NO;//取消双击缩放 self.barChartView.dragEnabled = YES;//启用拖拽图表 self.barChartView.dragDecelerationEnabled = YES;//拖拽后是否有惯性效果 self.barChartView.dragDecelerationFrictionCoef = 0.9;//拖拽后惯性效果的摩擦系数(0~1),数值越小,惯性越不明显 //X轴样式 ChartXAxis *xAxis = self.barChartView.xAxis; xAxis.axisLineWidth = 1;//设置X轴线宽 xAxis.labelPosition = XAxisLabelPositionBottom;//X轴的显示位置,默认是显示在上面的 xAxis.drawGridLinesEnabled = NO;//不绘制网格线 xAxis.spaceBetweenLabels = 4;//设置label间隔,若设置为1,则如果能全部显示,则每个柱形下面都会显示label xAxis.labelTextColor = [UIColor brownColor];//label文字颜色 //右边Y轴样式 self.barChartView.rightAxis.enabled = NO;//不绘制右边轴 //左边Y轴样式 ChartYAxis *leftAxis = self.barChartView.leftAxis;//获取左边Y轴 leftAxis.labelCount = 5;//Y轴label数量,数值不一定,如果forceLabelsEnabled等于YES, 则强制绘制制定数量的label, 但是可能不平均 leftAxis.forceLabelsEnabled = NO;//不强制绘制制定数量的label leftAxis.showOnlyMinMaxEnabled = NO;//是否只显示最大值和最小值 leftAxis.axisMinValue = 0;//设置Y轴的最小值 leftAxis.startAtZeroEnabled = YES;//从0开始绘制 leftAxis.axisMaxValue = 105;//设置Y轴的最大值 leftAxis.inverted = NO;//是否将Y轴进行上下翻转 leftAxis.axisLineWidth = 0.5;//Y轴线宽 leftAxis.axisLineColor = [UIColor blackColor];//Y轴颜色 leftAxis.valueFormatter = [[NSNumberFormatter alloc] init];//自定义格式 leftAxis.valueFormatter.positiveSuffix = @" $";//数字后缀单位 leftAxis.labelPosition = YAxisLabelPositionOutsideChart;//label位置 leftAxis.labelTextColor = [UIColor brownColor];//文字颜色 leftAxis.labelFont = [UIFont systemFontOfSize:10.0f];//文字字体 //网格线样式 leftAxis.gridLineDashLengths = @[@3.0f, @3.0f];//设置虚线样式的网格线 leftAxis.gridColor = [UIColor colorWithRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1];//网格线颜色 leftAxis.gridAntialiasEnabled = YES;//开启抗锯齿 //添加限制线 ChartLimitLine *limitLine = [[ChartLimitLine alloc] initWithLimit:80 label:@"限制线"]; limitLine.lineWidth = 2; limitLine.lineColor = [UIColor greenColor]; limitLine.lineDashLengths = @[@5.0f, @5.0f];//虚线样式 limitLine.labelPosition = ChartLimitLabelPositionRightTop;//位置 [leftAxis addLimitLine:limitLine];//添加到Y轴上 leftAxis.drawLimitLinesBehindDataEnabled = YES;//设置限制线绘制在柱形图的后面 //图例说明样式 self.barChartView.legend.enabled = NO;//不显示图例说明 // self.barChartView.legend.position = ChartLegendPositionBelowChartLeft;//位置 //右下角的description文字样式 self.barChartView.descriptionText = @"";//不显示,就设为空字符串即可 // self.barChartView.descriptionText = @"柱形图"; self.data = [self setData]; //为柱形图提供数据 self.barChartView.data = self.data; //设置动画效果,可以设置X轴和Y轴的动画效果 [self.barChartView animateWithYAxisDuration:1.0f]; } //为柱形图设置数据 - (BarChartData *)setData{ int xVals_count = 12;//X轴上要显示多少条数据 double maxYVal = 100;//Y轴的最大值 //X轴上面需要显示的数据 NSMutableArray *xVals = [[NSMutableArray alloc] init]; for (int i = 0; i < xVals_count; i++) { [xVals addObject:[NSString stringWithFormat:@"%d月", i+1]]; } //对应Y轴上面需要显示的数据 NSMutableArray *yVals = [[NSMutableArray alloc] init]; for (int i = 0; i < xVals_count; i++) { double mult = maxYVal + 1; double val = (double)(arc4random_uniform(mult)); BarChartDataEntry *entry = [[BarChartDataEntry alloc] initWithValue:val xIndex:i]; [yVals addObject:entry]; } //创建BarChartDataSet对象,其中包含有Y轴数据信息,以及可以设置柱形样式 BarChartDataSet *set1 = [[BarChartDataSet alloc] initWithYVals:yVals label:nil]; set1.barSpace = 0.2;//柱形之间的间隙占整个柱形(柱形+间隙)的比例 set1.drawValuesEnabled = YES;//是否在柱形图上面显示数值 set1.highlightEnabled = NO;//点击选中柱形图是否有高亮效果,(双击空白处取消选中) [set1 setColors:ChartColorTemplates.material];//设置柱形图颜色 //将BarChartDataSet对象放入数组中 NSMutableArray *dataSets = [[NSMutableArray alloc] init]; [dataSets addObject:set1]; //创建BarChartData对象, 此对象就是barChartView需要最终数据对象 BarChartData *data = [[BarChartData alloc] initWithXVals:xVals dataSets:dataSets]; [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:10.f]];//文字字体 [data setValueTextColor:[UIColor orangeColor]];//文字颜色 NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; //自定义数据显示格式 [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; [formatter setPositiveFormat:@"#0.0"]; [data setValueFormatter:formatter]; return data; } -(void)updateData{ //数据改变时,刷新数据 self.data = [self setData]; self.barChartView.data = self.data; [self.barChartView notifyDataSetChanged]; } #pragma mark - ChartViewDelegate //点击选中柱形时回调 - (void)chartValueSelected:(ChartViewBase * _Nonnull)chartView entry:(ChartDataEntry * _Nonnull)entry dataSetIndex:(NSInteger)dataSetIndex highlight:(ChartHighlight * _Nonnull)highlight{ NSLog(@"---chartValueSelected---value: %g", entry.value); } //没有选中柱形图时回调,当选中一个柱形图后,在空白处双击,就可以取消选择,此时会回调此方法 - (void)chartValueNothingSelected:(ChartViewBase * _Nonnull)chartView{ NSLog(@"---chartValueNothingSelected---"); } //放大图表时回调 - (void)chartScaled:(ChartViewBase * _Nonnull)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY{ NSLog(@"---chartScaled---scaleX:%g, scaleY:%g", scaleX, scaleY); } //拖拽图表时回调 - (void)chartTranslated:(ChartViewBase * _Nonnull)chartView dX:(CGFloat)dX dY:(CGFloat)dY{ NSLog(@"---chartTranslated---dX:%g, dY:%g", dX, dY); } @end
相关文章推荐
- 安卓系统上制作图表的框架 AChartEngine
- Winform开发框架之统计图表的实现
- Android绘图机制(四)——使用HelloCharts开源框架搭建一系列炫酷图表,柱形图,折线图,饼状图和动画特效,抽丝剥茧带你认识图表之美
- Android 图表开源框架HelloCharts 之 柱状图、折线图、饼状图,Fragment
- Android 统计框架hellocharts
- FusionChartsFree 柱状统计图表实现
- Android : hellocharts-android-master图表框架集成 及 新手花式教学(干货满满)------柱状图
- 图表框架HelloCharts(2)柱状图
- 图表框架HelloCharts(1)线形图
- Android 一个酷炫的图表制作框架
- Winform开发框架之统计图表的实现
- 如何在 Swift 语言下使用 iOS Charts API 制作漂亮图表?
- [转载]Winform开发框架之统计图表的实现
- 图表框架HelloCharts(3)饼状图
- 使用delphi制作统计图表,delphi PageControl选项卡标题变色
- 图表制作Charts
- 教你如何制作excel透视图表方便管理员工加班统计信息
- android图表框架XCL-Charts使用方法
- Django 图表制作(By Highcharts)
- 一个酷炫的Android图表制作框架