iOS(とかOSX)でグラフを書けるCorePlotいいよー。オプションとかいろいろあって煩雑だけどそこはさておいて簡潔にまとめてみようと思います。

まずは導入編

CocoaPods使いましょう。

1pod 'CorePlot'

からの$ pod installでいけます。

散布図、折れ線グラフ

サンプルとしてグラフは2つ書きました。Aがオプションをできるだけ省略したほう、Bがオプションをいくつか付けてみたほうです。配列に20個のランダムな整数値を入れ、配列のインデックスを横軸、その値を縦軸にとった折れ線のグラフを描画しました。

ちゃんと使うにはグラフ用のUIViewクラスを作ってラップしたほうがいいと思いますが、今回はそれも面倒なのでViewControllerに直接書きます!

散布図を載せたいViewControllerを作ってヘッダーにはプロトコルの指定とプロット用データ置き場を書き加えました。Objective-CのArrayはちょっと面倒なので、、、なお、C++のコードなのでViewControllerの拡張子は.mmにしておく必要があります。

 1#import <UIKit/UIKit.h>
 2#import <CorePlot/CorePlot-CocoaTouch.h>
 3#import <vector>
 4
 5@interface ScatterViewController : UIViewController<CPTPlotDataSource>
 6{
 7    std::vector<int> _dataA;
 8    std::vector<int> _dataB;
 9}
10
11@end 

次に実装ファイルのほう。

グラフ領域やオプションなどの初期設定はviewDidLoadで行いました。

1- (void)viewDidLoad
2{
3    [super viewDidLoad];
4     // Do any additional setup after loading the view.
5   
6    // CorePlotのセットアップ
7    [self setupPlotA];
8    [self setupPlotB];
9} 

グラフA

次にグラフA用のセットアップです。

 1- (void)setupPlotA
 2{
 3    CGRect rect = CGRectMake(0, 100, 320, 100);
 4    CPTGraphHostingView* hostingView = [[CPTGraphHostingView alloc] initWithFrame:rect];
 5    CPTGraph* graph = [[CPTXYGraph alloc] initWithFrame:rect];
 6    hostingView.hostedGraph = graph;
 7   
 8    CPTScatterPlot* plot = [[CPTScatterPlot alloc] init];
 9    plot.identifier = @"A";
10    plot.dataSource = self;
11    [graph addPlot:plot];
12   
13    CPTXYPlotSpace* space = (CPTXYPlotSpace*)graph.defaultPlotSpace;
14    space.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(100)];
15    space.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(19)];
16    [self.view addSubview:hostingView];
17   
18    // プロット用データのセットアップ
19    _dataA.clear();
20    for(int i=0; i<20; ++i){
21        _dataA.push_back(rand()%100);
22    }
23} 

いくつかCorePlotのクラスが登場しました。

  • CPTGraphHostingView
    グラフが描画されるUIViewで親のViewにaddSubviewされます
  • CPTGraph
    グラフのメタデータ?的なものです。グラフ全体を管理しているイメージ
  • CPTScatterPlot
    データをどのように処理するか(描画するか)ということを扱っているクラス(というイメージ)

大雑把に言うと、CPTScatterPlotCPTGraphにセットして、CPTGraphCPTGraphHostingViewにセット、そのCPTGraphHostingVIewaddSubviewするという流れです。

グラフB

グラフBではオプションをいくつか設定しました。本当はもっとたくさんのオプションがあるのですが、把握しきれないため適当にいくつか選んでいじっています。

 1- (void)setupPlotB
 2{
 3    CGRect rect = CGRectMake(0, 210, 320, 200);
 4    CPTGraphHostingView* hostingView = [[CPTGraphHostingView alloc] initWithFrame:rect];
 5    CPTGraph* graph = [[CPTXYGraph alloc] initWithFrame:rect];
 6    hostingView.hostedGraph = graph;
 7   
 8    CPTScatterPlot* plot = [[CPTScatterPlot alloc] init];
 9    plot.identifier = @"B";
10    plot.dataSource = self;
11    [graph addPlot:plot];
12   
13    CPTXYPlotSpace* space = (CPTXYPlotSpace*)graph.defaultPlotSpace;
14    space.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(100)];
15    space.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(19)];
16    [self.view addSubview:hostingView];
17   
18    // プロット用データのセットアップ
19    _dataB.clear();
20    for(int i=0; i<20; ++i){
21        _dataB.push_back(rand()%50);
22    }
23   
24    // いろいろ設定
25    graph.plotAreaFrame.paddingBottom = 50;
26    graph.plotAreaFrame.paddingLeft = 50;
27    graph.plotAreaFrame.paddingTop = 10;
28    graph.plotAreaFrame.paddingRight = 10;
29   
30    // 軸の設定
31    CPTXYAxisSet* axisSet = (CPTXYAxisSet*)graph.axisSet;
32    CPTMutableLineStyle* style = [CPTMutableLineStyle lineStyle];
33    style.lineColor = [CPTColor orangeColor];
34    style.lineWidth = 2;
35    axisSet.xAxis.axisLineStyle = style;
36    axisSet.yAxis.axisLineStyle = style;
37   
38    CPTXYAxis* xAxis = axisSet.xAxis;
39    xAxis.majorIntervalLength = CPTDecimalFromInt(5);
40   
41    NSNumberFormatter* tickFormatter = [[NSNumberFormatter alloc] init];
42    [tickFormatter setGeneratesDecimalNumbers:NO];
43    [tickFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
44    xAxis.labelFormatter = tickFormatter;
45   
46    xAxis.title = @"X軸";
47   
48    CPTXYAxis* yAxis = axisSet.yAxis;
49    yAxis.majorIntervalLength = CPTDecimalFromInt(20);
50   
51    yAxis.title = @"Y軸";
52   
53    // プロットの設定
54    plot.dataLineStyle = nil;
55    plot.plotSymbol = [CPTPlotSymbol diamondPlotSymbol];
56} 

すごく長くなってしまうのがわかりますね。正直、ここは結構面倒です。

DataSourceのメソッド

さきほどまでのコードでは、肝心のグラフに載せるためのデータはほとんど登場しません。せいぜいランダムな値をvectorに追加したぐらい。CorePlotではデータを返すメソッドを使います。TableViewみたいな感じで。

  • numberForPlot
    プロット用の値で、ScatterPlotの場合はidxに対応したXの値またはYの値を返します
  • numberOfRecordsForPlat
    プロットの項目数を返してあげます
 1- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
 2{
 3    NSNumber* num;
 4    switch (fieldEnum) {
 5        case CPTScatterPlotFieldX:
 6            num = [NSNumber numberWithInt:idx];
 7            break;
 8        case CPTScatterPlotFieldY:
 9            // plot.identifierで分岐することで、2種類以上のグラフを同じDataSourceクラスで書くことができる
10            if([(NSString*)plot.identifier isEqualToString:@"A"]){
11                num = [NSNumber numberWithInt:_dataA[idx]];
12            }else{
13                num = [NSNumber numberWithInt:_dataB[idx]];
14            }
15            break;
16    }
17    return num;
18}
19
20- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
21{
22    if([(NSString*)plot.identifier isEqualToString:@"A"]){
23        return (int)_dataA.size();
24    }
25    return (int)_dataB.size();
26}

今回の例ではグラフA、Bという2つのグラフが登場します。これらはどちらも同じDataSourceメソッドを使うことになるので、plot.identifierを使ってどちらのグラフのための情報を返すときなのかを判別して値を返しています。

円グラフ

こんな感じのグラフを書けます。

ヘッダーファイル

ヘッダーはこんな感じ。基本は似通っています。

 1#import <UIKit/UIKit.h>
 2#import <CorePlot/CorePlot-CocoaTouch.h>
 3#import <vector>
 4
 5@interface PieViewController : UIViewController<CPTPieChartDataSource,CPTPieChartDelegate>
 6{
 7    std::vector<float> _data;
 8}
 9
10@end 

実装ファイル

実装はこんな感じです。CPTScatterPlotの変わりにCPTPieChartが登場し(どちらも同じ親クラスを持ちます)、それに関連した設定が必要となっています。

また、CPTThemeという概念があって、グラフのビジュアルをいくつかのテーマに基づいて切り替えることができます。

 1- (void)setupChartA
 2{
 3    CGRect rect = CGRectMake(10, 40, 300, 300);
 4    CPTGraphHostingView* hostingView = [[CPTGraphHostingView alloc] initWithFrame:rect];
 5    CPTGraph* graph = [[CPTXYGraph alloc] initWithFrame:rect];
 6    graph.axisSet = nil;
 7    hostingView.hostedGraph = graph;
 8    [self.view addSubview:hostingView];
 9   
10    CPTTheme* theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
11    [graph applyTheme:theme];
12   
13    CPTPieChart* plot = [[CPTPieChart alloc] init];
14    plot.identifier = @"PIE";
15    plot.dataSource = self;
16    plot.delegate = self;
17    [graph addPlot:plot];
18   
19    plot.pieRadius = 100;
20
21    _data.clear();
22    _data.push_back(50);
23    _data.push_back(20);
24    _data.push_back(15);
25    _data.push_back(3);
26    _data.push_back(12);
27} 

データソース

円グラフの場合は2次元ではないので返す値は場合分けの必要はありません。

1- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
2{
3    return [NSNumber numberWithFloat:_data[idx]];
4}

棒グラフ

こんなグラフを書けます。使ったテーマが悪いのか、めちゃくちゃシンプルだな、、

長くなったのでソースは省略します。以下にサンプルアプリ一式があるのでどぞー。 pi-chan/CorePlotExample