CorePlot画表数据

CPTGraphHostingView   ----- CPTXYGraph -----  CPTBarPlot/CPTScatterPlot ---- CPTXYPlotSpace CPTXYAxisSet  CPTPlotRange  CPTTheme 


使用corePlot实现股票图

- (void)viewDidLoad

{

    [super viewDidLoad];

    graph = [[CPTXYGraph allocinitWithFrame:self.view.bounds];

    

    //设置画板主题

    CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];

    [graph applyTheme:theme];

    

    //创建一个可以添加画板的视图

    CPTGraphHostingView *hostingView = [[CPTGraphHostingView allocinitWithFrame:self.view.bounds];

    hostingView.hostedGraph = graph;

    [self.view addSubview:hostingView];

    [hostingView release];

    

    //设置边界

    graph.paddingLeft = 0;

    graph.paddingRight = 0;

    graph.paddingTop = 0;

    graph.paddingBottom = 0;

    graph.plotAreaFrame.paddingLeft = 45.0;

    graph.plotAreaFrame.paddingRight = 5.0;

    graph.plotAreaFrame.paddingBottom = 80.0;

    graph.plotAreaFrame.paddingTop = 40.0;

    

    //设置坐标范围

    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;

    plotSpace.allowsUserInteraction = NO;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0length:CPTDecimalFromFloat(200.0)];

    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0length:CPTDecimalFromFloat(200.0)];

    

    //设置坐标刻度大小

    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;

    CPTXYAxis *x = axisSet.xAxis;

    CPTXYAxis *y = axisSet.yAxis;

    x.minorTickLineStyle = nil;

    y.minorTicksPerInterval = 5.0f;

    x.majorIntervalLength = CPTDecimalFromString(@"50");

    y.majorIntervalLength = CPTDecimalFromString(@"50");

    x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");//坐标原点

    y.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");

    

    //创建绿色区域

    dataSourceLinePlot = [[[CPTScatterPlot allocinitautorelease];

    dataSourceLinePlot.identifier = @"Green Plot";

    //设置绿色区域边框样式

    CPTMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopyautorelease];

    lineStyle.lineWidth = 2.0f;

    lineStyle.lineColor = [CPTColor redColor];

    dataSourceLinePlot.dataLineStyle = lineStyle;

    dataSourceLinePlot.opacity = 0.0f//未添加动画而准备

    dataSourceLinePlot.interpolation = CPTScatterPlotInterpolationCurved;

    

    //添加数据点到图形上

    dataSourceLinePlot.dataSource = self;

    [graph addPlot:dataSourceLinePlot];

    

    //创建颜色渐变和填充 

    CPTGradient *areaGradient = [CPTGradient gradientWithBeginningColor:[CPTColor redColorendingColor:[CPTColor colorWithComponentRed:0.65 green:0.65 blue:0.16 alpha:0.2]];

    areaGradient.angle = - 90.0f;//渐变角度(顺时针旋转)

    CPTFill *areaGradientFill = [CPTFill fillWithGradient:areaGradient];//颜色填充

    dataSourceLinePlot.areaFill = areaGradientFill;

    dataSourceLinePlot.areaBaseValue = CPTDecimalFromString(@"0.0");// 填充区域底部高度

    

    dataForPlot1 = [[NSMutableArray allocinit];

    j = 200;

    r = 0;

    timer1 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dataOpt) userInfo:nil repeats:YES];

    [timer1 fire];

}

- (void)dataOpt

{

    //添加随机数

    if ([dataSourceLinePlot.identifier isEqual:@"Green Plot"])

    {

        NSString *xp = [NSString stringWithFormat:@"%d",j];

        NSString *yp = [NSString stringWithFormat:@"%d",(rand()%200)];

        NSMutableDictionary *point1 = [[NSMutableDictionary allocinitWithObjectsAndKeys:xp,@"x",yp,@"y"nil];

        [dataForPlot1 insertObject:point1 atIndex:0];

    }

    //刷新画板

    [graph reloadData];

    j += 20;

    r += 20;

}

- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot

{

    return [dataForPlot1 count];

}

- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx

{

    NSString *key = (fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y");

    NSNumber *num = (NSNumber *)[[dataForPlot1 objectAtIndex:idx] valueForKey:key];

    

    //让视图偏移

    if ([(NSString *)plot.identifier isEqualToString:@"Green Plot"])

    {

        

        if (fieldEnum == CPTScatterPlotFieldX)

        {

            num = [NSNumber numberWithDouble:[num doubleValue]-r];

        }

    }

    

    CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];

    fadeInAnimation.duration = 1.0;

    fadeInAnimation.removedOnCompletion = NO;

    fadeInAnimation.fillMode = kCAFillModeForwards;

    fadeInAnimation.toValue = [NSNumber numberWithFloat:2.0];

    [dataSourceLinePlot addAnimation:fadeInAnimation forKey:@"animateOpacity"];

    

    return num;

}


使用corePlot实现柱图

1. 初始化的动作

    // create the graph
    CPTGraphHostingView *chartLayout=[[CPTGraphHostingView alloc] initWithFrame:CGRectMake(320, 0, self.frame.size.width, self.frame.size.height-BUTTON_LAYOUT_HEIGHT)];
    chartLayout.backgroundColor=[UIColor whiteColor];
    
    graph=[[CPTXYGraph alloc] initWithFrame:chartLayout.bounds];
    graph.plotAreaFrame.masksToBorder=NO;
    chartLayout.hostedGraph=graph;
    //configure the graph
    [graph applyTheme:[CPTTheme themeNamed:kCPTPlainWhiteTheme]];
    // graph在hostingView中的偏移
    graph.paddingBottom=5.0f;
    graph.paddingLeft=5.0f;
    graph.paddingRight=5.0f;
    graph.paddingTop=5.0f;
    graph.plotAreaFrame.borderLineStyle=nil;
    graph.plotAreaFrame.cornerRadius=0.0f;// hide frame
    // 绘图区4边留白
    graph.plotAreaFrame.paddingTop=5.0;
    graph.plotAreaFrame.paddingRight=5.0;
    graph.plotAreaFrame.paddingLeft=50.0;
    graph.plotAreaFrame.paddingBottom=30.0;
    //设置title
    
    // set up the plots
    CPTBarPlot *plot=[CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:NO];
    // set up line style
    CPTMutableLineStyle *barLineStyle=[[CPTMutableLineStyle alloc] init];
    barLineStyle.lineColor=[CPTColor blackColor];
    barLineStyle.lineWidth=1.0;
    // set up text style
    CPTMutableTextStyle *textLineStyle=[CPTMutableTextStyle textStyle];
    textLineStyle.color=[CPTColor blackColor];
    //set up plot space
    CGFloat xMin=0.1f;
    CGFloat xMax=7.9f;
    CGFloat yMin=0.1f;
    CGFloat yMax=7500.0f;
    CPTXYPlotSpace *plotSpace=(CPTXYPlotSpace *)graph.defaultPlotSpace;
    plotSpace.xRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xMin) length:CPTDecimalFromFloat(xMax)];
    plotSpace.yRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(yMin) length:CPTDecimalFromFloat(yMax)];
    
    // add plots to graph
    plot.dataSource=self;
    plot.delegate=self;  // 如果不需要柱状图的选择,这条语句是没必要的
    plot.baseValue=CPTDecimalFromInt(0); // 设定基值,大于该值的从此点向上画,小于该值的反向绘制,即向下画
    plot.barWidth=CPTDecimalFromDouble(0.5); // 设定柱图的宽度(0.0~1.0)
    plot.barOffset=CPTDecimalFromDouble(-0.0); // 柱图每个柱子开始绘制的偏移位置,我们让它绘制在刻度线中间,所以不偏移
    plot.lineStyle=barLineStyle;
    
    // set axis
    CPTXYAxisSet *axisSet=(CPTXYAxisSet *)graph.axisSet;
    // xAxis
    CPTXYAxis   *xAxis=axisSet.xAxis;
    CPTMutableLineStyle *xLineStyle=[[CPTMutableLineStyle alloc] init];
    xLineStyle.lineColor=[CPTColor blackColor];
    xLineStyle.lineWidth=1.0f;
    xAxis.axisLineStyle=xLineStyle;
    xAxis.labelingPolicy=CPTAxisLabelingPolicyNone;
    xAxis.axisConstraints=[CPTConstraints constraintWithLowerOffset:0.0];// 加上这两句才能显示label
    xAxis.majorTickLineStyle=xLineStyle; //X轴大刻度线,线型设置
    xAxis.majorTickLength=5;  // 刻度线的长度
    xAxis.majorIntervalLength=CPTDecimalFromInt(1); // 间隔单位,和xMin~xMax对应
    // 小刻度线minor...
    xAxis.minorTickLineStyle=nil;
    xAxis.orthogonalCoordinateDecimal=CPTDecimalFromInt(0);
    
    // yAxis
    CPTXYAxis   *yAxis=axisSet.yAxis;
    yAxis.axisLineStyle=xLineStyle;
    yAxis.majorTickLineStyle=xLineStyle; //X轴大刻度线,线型设置
    yAxis.majorTickLength=5;  // 刻度线的长度
    yAxis.majorIntervalLength=CPTDecimalFromInt(300); // 间隔单位,和yMin~yMax对应
    // 小刻度线minor...
    yAxis.minorTickLineStyle=nil;  //  不显示小刻度线
    yAxis.orthogonalCoordinateDecimal=CPTDecimalFromInt(0);
    
    // 设置X轴label
    NSMutableArray *labelArray=[NSMutableArray arrayWithCapacity:7];
    NSArray        *conArray=[NSArray arrayWithObjects:@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六",@"星期日", nil];
    int labelLocation=1;
    for(NSString *label in conArray){
        CPTAxisLabel *newLabel=[[CPTAxisLabel alloc] initWithText:label textStyle:xAxis.labelTextStyle];
        newLabel.tickLocation=[[NSNumber numberWithInt:labelLocation] decimalValue];
        newLabel.offset=xAxis.labelOffset+xAxis.majorTickLength;
        newLabel.rotation=M_PI/6;
        [labelArray addObject:newLabel];
        labelLocation++;
        [newLabel release];
    }
    xAxis.axisLabels=[NSSet setWithArray:labelArray];
    
    [graph addPlot:plot toPlotSpace:graph.defaultPlotSpace];  // 将plot添加到默认的空间中
    [self addSubview:chartLayout];

2. 实现CPTBarPlotDataSource协议方法

#pragma mark - CPTBarPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot{
        return 7;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
    NSNumber *num=nil;
    if ([plot isKindOfClass:[CPTBarPlot class]]) {
       NSMutableDictionary *tempDic=[self.mArray objectAtIndex:index];
        switch (fieldEnum) {
            case CPTBarPlotFieldBarLocation:
                num=[NSNumber numberWithInt:index+1];    // X轴上的数值表示
                break;
            case CPTBarPlotFieldBarTip:
                num=[NSDecimalNumber numberWithInt:[[mArray objectAtIndex:index] intValue]];                

               break;
            default:
                break;
        }
    }
    return num;
}
//-(CPTFill *)barFillForBarPlot:(CPTBarPlot *)barPlot recordIndex:(NSUInteger)index{
//    return nil;
//}

// 在柱子上面显示对应的值
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index{
    CPTMutableTextStyle *textLineStyle=[CPTMutableTextStyle textStyle];
    textLineStyle.fontSize=14;
    textLineStyle.color=[CPTColor blackColor];
    NSMutableDictionary *tempDic=[self.mArray objectAtIndex:index];
    CPTTextLayer *label=[[CPTTextLayer alloc] initWithText:[mArray objectAtIndex:index] style:textLineStyle];
    return label;
}

三,效果图

注:此图数据和我具体的项目有关,所以如果你单纯的复制上面的代码产生不了此图,我只是给出其中最核心的代码,如果有任何方面的疑问和交流,请留言

 

 

-------------对 软件456 的回复

 

需要注意的几个地方:
1. plotSpace.yRange:这个地方你要设置正确,然后才能显示完整。
如依据上图,我的设置为:
CGFloat yMin=-1000.0f;

CGFloat yMax=1500.0f;
plotSpace.yRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(yMin) 

length:CPTDecimalFromFloat(yMax-yMin)];

2. 轴上的数据显示
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index{
CPTMutableTextStyle 

*textLineStyle=[CPTMutableTextStyle textStyle];
textLineStyle.fontSize=14;

textLineStyle.color=[CPTColor blackColor];
// NSMutableDictionary *tempDic=[self.mArray 

objectAtIndex:index];
// CPTTextLayer *label=[[CPTTextLayer alloc] initWithText:[tempDic 

objectForKey:KEY] style:textLineStyle];
CPTTextLayer *label=[[CPTTextLayer alloc] initWithText:

[NSString stringWithFormat:@"%d",-600+300*index] style:textLineStyle];
return [label 

autorelease];
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的例子,展示如何使用Python中的一些常用数据可视化库画出雷达图、柱状图、词云和饼图,并创建数据可视化大屏: 1. 雷达图 ```python import matplotlib.pyplot as plt import numpy as np # 创建数据 categories = ['A', 'B', 'C', 'D', 'E'] values = [5, 3, 4, 2, 6] # 计算角度 angles = np.linspace(0, 2*np.pi, len(categories), endpoint=False) # 闭合图形 values = np.concatenate((values, [values[0]])) angles = np.concatenate((angles, [angles[0]])) # 创建雷达图 fig = plt.figure() ax = fig.add_subplot(111, polar=True) ax.plot(angles, values, 'o-', linewidth=2) ax.fill(angles, values, alpha=0.25) ax.set_thetagrids(angles * 180/np.pi, categories) ax.grid(True) # 显示图像 plt.show() ``` 2. 柱状图 ```python import matplotlib.pyplot as plt # 创建数据 x = ['A', 'B', 'C', 'D', 'E'] y = [5, 3, 4, 2, 6] # 创建柱状图 fig, ax = plt.subplots() ax.bar(x, y) # 添加标签和标题 ax.set_xlabel('Categories') ax.set_ylabel('Values') ax.set_title('Example Bar Chart') # 显示图像 plt.show() ``` 3. 词云 ```python from wordcloud import WordCloud import matplotlib.pyplot as plt # 创建词云 text = "Hello World! This is an example text for wordcloud." wordcloud = WordCloud().generate(text) # 显示词云 plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show() ``` 4. 饼图 ```python import matplotlib.pyplot as plt # 创建数据 labels = ['A', 'B', 'C', 'D', 'E'] sizes = [5, 3, 4, 2, 6] # 创建饼图 fig, ax = plt.subplots() ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90) # 添加标题 ax.set_title('Example Pie Chart') # 显示图像 plt.show() ``` 5. 创建数据可视化大屏 一般来说,创建数据可视化大屏需要用到前端技术和可视化库,比如D3.js、Echarts等。这里提供一个简单的Python库dash,可以用Python代码创建交互式的数据可视化大屏。 ```python import dash import dash_core_components as dcc import dash_html_components as html # 创建app app = dash.Dash() # 创建布局 app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='example-graph', figure={ 'data': [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Category 1'}, {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': 'Category 2'}, ], 'layout': { 'title': 'Example Dash Plot' } } ) ]) # 启动app if __name__ == '__main__': app.run_server(debug=True) ``` 上面的代码创建了一个简单的Dash应用,包括一个标题、一个段落和一个柱状图。你可以根据需要修改这个例子,添加更多的组件和布局,创建你需要的数据可视化大屏。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值