如何在Bar底部显示标签 - Core Plot?

时间:2014-03-10 10:40:58

标签: ios core-plot

如何在底部栏上显示标签?, 我使用下面的方法并设置labeloffset,但它在顶部显示标签 (在图像标签文本中,“测试”显示在条形图的中间,但我需要显示底部)。

enter image description here

-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index
{
 static CPTMutableTextStyle *labelText = nil;

if ( !labelText ) {
    labelText       = [[CPTMutableTextStyle alloc] init];
    labelText.color = [CPTColor redColor];
}

NSString *labelValue = @"Test";

NSDictionary *testsDict = [assmentsTestsForGraphArray objectAtIndex:index];
NSInteger score = [[testsDict valueForKey:@"Score"] integerValue];

CPTTextLayer *newLayer = [[CPTTextLayer alloc] initWithText:labelValue style:labelText];

plot.labelOffset = -score;//0;//-10;

 return newLayer;
}

2 个答案:

答案 0 :(得分:1)

至少有三种不同的方法可以做到这一点:

  1. 创建第二个图(条形图或散点图;它并不重要)并为其赋予与原始图相同的x值,但将所有y值设置为等于垂直图x轴的位置。标记第二个图而不是第一个图。设置第二个图,这样它就不会绘制除标签之外的任何内容,即将所有线条样式和填充设置为nil

  2. 在x轴上使用自定义轴标签,而不是绘制数据标签。

  3. 为每个标签而不是绘图数据标签创建绘图空间注释。

答案 1 :(得分:0)

抱歉,我昨天没想好。我的第一个答案的开头保持不变。

条形图的标签(根据我非常有限的知识)设置为条形图的最大值。因此,为了使标签偏移到图形的底部,您需要提出一种适用于您所拥有的图形的算法。在我看来,当fieldEnum是CPTBarPlotFieldBarTip时,设置偏移量的最佳位置是numberForPlot委托函数。我不能花很多时间搞清楚正确的算法,但是如果你使用Plot_Gallery_iOS示例项目并编辑VerticalBarChart.m,你会发现你必须使用的各种偏移量。这是我找到的一点点:

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

    if ( fieldEnum == CPTBarPlotFieldBarLocation ) {
        // location
        if ( [plot.identifier isEqual:@"Bar Plot 2"] ) {
            num = [NSDecimalNumber numberWithInt:index];
        }
        else {
            num = [NSDecimalNumber numberWithInt:index];
        }
    }
    else if ( fieldEnum == CPTBarPlotFieldBarTip ) {
        // length
        if ( [plot.identifier isEqual:@"Bar Plot 2"] ) {
            num = [NSDecimalNumber numberWithInt:index];
        }
        else {
            num = [NSDecimalNumber numberWithInt:(index + 1) * (index + 1)];
            plot.labelOffset = -1.0;
            //-1.0 works well for the first bar, -345.0 works well for the last bar
        }
    }
    else {
        // base
        if ( [plot.identifier isEqual:@"Bar Plot 2"] ) {
            num = [NSDecimalNumber numberWithInt:0];
        }
        else {
            num = [NSDecimalNumber numberWithInt:index];
        }
    }

    return num;
}

-1.0适用于第一个条形图(高度为1个单位),-345.0适用于最后一个条形图(高度为100个单位)。对不起我昨天带你走错了方向,我没有足够的时间来帮助你提出一个好的算法,但希望这有助于你找到正确的方向。