草庐IT

iOS CorePlot x 轴 DateTime 间隔成比例

coder 2024-01-25 原文

我有代码显示带有两个图的图表。我想要但没有找到该怎么做的是:在 x 轴上 DateTime 的位置我需要日期之间的正确比例间隔,而不是相同的。 这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    DateTime = @[@"2013-10-05 08:47:52",@"2013-10-06 08:47:52",@"2013-10-07 08:47:52",@"2013-10-08 08:47:52",@"2013-10-09 08:47:52",@"2013-10-12 08:47:52",@"2013-10-13 08:47:52"];
    temp1 = @[@"17.1",@"20",@"19",@"16",@"15",@"15",@"17"];
    temp2 = @[@"13",@"11",@"13",@"10",@"11",@"12",@"13"];
    [self initPlot];
}
-(void)initPlot
{
    [self configureHost];
    [self configureGraph];
    [self configurePlots];
    [self configureAxes];
}
-(void)configureHost
{
    self.hostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
    self.hostView.allowPinchScaling = YES;
    [self.view addSubview:self.hostView];
}
-(void)configureGraph
{
    // 1 - Create the graph
    CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
    [graph applyTheme:[CPTTheme themeNamed:kCPTSlateTheme]];
    self.hostView.hostedGraph = graph;
    // 2 - Set graph title
    NSString *title = @"Testovací graf";
    graph.title = title;
    // 3 - Create and set text style
    CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
    titleStyle.color = [CPTColor blackColor];
    titleStyle.fontName = @"Helvetica-Bold";
    titleStyle.fontSize = 12.0f;
    graph.titleTextStyle = titleStyle;
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
    //graph.titleDisplacement = CGPointMake(0.0f, 10.0f);
    // 4 - Set padding for plot area
    [graph.plotAreaFrame setPaddingLeft:30.0f];
    [graph.plotAreaFrame setPaddingBottom:100.0f];
    // 5 - Enable user interactions for plot space
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
    plotSpace.allowsUserInteraction = YES;

}
-(void)configurePlots
{
    // 1 - Get graph and plot space
    CPTGraph *graph = self.hostView.hostedGraph;
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
    // 2 - Create the plots
    CPTScatterPlot *probe1Plot = [[CPTScatterPlot alloc] init];
    probe1Plot.dataSource = self;
    probe1Plot.identifier = @"Temp1";
    CPTColor *probe1Color = [CPTColor redColor];
    [graph addPlot:probe1Plot toPlotSpace:plotSpace];
    CPTScatterPlot *probe2Plot = [[CPTScatterPlot alloc] init];
    probe2Plot.dataSource = self;
    probe2Plot.identifier = @"Temp2";
    CPTColor *probe2Color = [CPTColor blueColor];
    [graph addPlot:probe2Plot toPlotSpace:plotSpace];
    // 3 - Set up plot space
    [plotSpace scaleToFitPlots:[NSArray arrayWithObjects:probe1Plot, probe2Plot, nil]];
    CPTMutablePlotRange *xRange = [plotSpace.xRange mutableCopy];
    [xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.48f)];
    plotSpace.xRange = xRange;
    CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
    [yRange expandRangeByFactor:CPTDecimalFromCGFloat(3.0f)];
    plotSpace.yRange = yRange;
    // 4 - Create styles and symbols
    CPTMutableLineStyle *probe1LineStyle = [probe1Plot.dataLineStyle mutableCopy];
    probe1LineStyle.lineWidth = 1.0  ;
    probe1LineStyle.lineColor = probe1Color;
    probe1Plot.dataLineStyle = probe1LineStyle;
    CPTMutableLineStyle *probe1SymbolLineStyle = [CPTMutableLineStyle lineStyle];
    probe1SymbolLineStyle.lineColor = probe1Color;
    CPTPlotSymbol *probe1Symbol = [CPTPlotSymbol ellipsePlotSymbol];
    probe1Symbol.fill = [CPTFill fillWithColor:probe1Color];
    probe1Symbol.lineStyle = probe1SymbolLineStyle;
    probe1Symbol.size = CGSizeMake(3.0f, 3.0f);
    probe1Plot.plotSymbol = probe1Symbol;

    CPTMutableLineStyle *probe2LineStyle = [probe2Plot.dataLineStyle mutableCopy];
    probe2LineStyle.lineWidth = 1.0;
    probe2LineStyle.lineColor = probe2Color;
    probe2Plot.dataLineStyle = probe2LineStyle;
    CPTMutableLineStyle *probe2SymbolLineStyle = [CPTMutableLineStyle lineStyle];
    probe2SymbolLineStyle.lineColor = probe2Color;
    CPTPlotSymbol *probe2Symbol = [CPTPlotSymbol diamondPlotSymbol];
    probe2Symbol.fill = [CPTFill fillWithColor:probe2Color];
    probe2Symbol.lineStyle = probe2SymbolLineStyle;
    probe2Symbol.size = CGSizeMake(3.0f, 3.0f);
    probe2Plot.plotSymbol = probe2Symbol;
}
-(void)configureAxes
{
    // 1 - Create styles
    CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
    axisTitleStyle.color = [CPTColor blackColor];
    axisTitleStyle.fontName = @"Helvetica-Bold";
    axisTitleStyle.fontSize = 10.0f;
    CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
    axisLineStyle.lineWidth = 1.5f;
    axisLineStyle.lineColor = [CPTColor blackColor];
    CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
    axisTextStyle.color = [CPTColor blackColor];
    axisTextStyle.fontName = @"Helvetica-Bold";
    axisTextStyle.fontSize = 11.0f;
    CPTMutableLineStyle *tickLineStyle = [CPTMutableLineStyle lineStyle];
    tickLineStyle.lineColor = [CPTColor blackColor];
    tickLineStyle.lineWidth = 2.0f;
    CPTMutableLineStyle *gridLineStyle = [CPTMutableLineStyle lineStyle];
    gridLineStyle.lineColor = [CPTColor grayColor];
    gridLineStyle.lineWidth = 0.5f;
    // 2 - Get axis set
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet;
    // 3 - Configure x-axis
    CPTAxis *x = axisSet.xAxis;
    x.title = @"DateTime";
    x.titleTextStyle = axisTitleStyle;
    x.titleOffset = 85.0f;
    x.axisLineStyle = axisLineStyle;
    x.labelingPolicy = CPTAxisLabelingPolicyNone;
    x.labelTextStyle = axisTextStyle;
    x.majorTickLineStyle = axisLineStyle;
    x.majorTickLength = 4.0f;
    x.tickLabelDirection = CPTSignNegative;

    CGFloat dateCount = [DateTime count];
    NSMutableSet *xLabels = [NSMutableSet setWithCapacity:dateCount];
    NSMutableSet *xLocations = [NSMutableSet setWithCapacity:dateCount];
    NSInteger i = 0;
    for (NSString *date in DateTime)
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateStyle:NSDateFormatterShortStyle];
        NSString *str = [self localTime:date];
        CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:str textStyle:x.labelTextStyle];
        CGFloat location = i++;
        label.tickLocation = CPTDecimalFromCGFloat(location);
        label.offset = x.majorTickLength;

        if (label)
        {
            [xLabels addObject:label];
            [xLocations addObject:[NSNumber numberWithFloat:location]];
        }
    }

    x.axisLabels = xLabels;
    x.majorTickLocations = xLocations;
    x.labelRotation = M_PI / 4;

    // 4 - Configure y-axis
    CPTAxis *y = axisSet.yAxis;
    y.title = @"Temperature";
    y.titleTextStyle = axisTitleStyle;
    y.titleOffset = 30.0f;
    y.axisLineStyle = axisLineStyle;
    y.majorGridLineStyle = gridLineStyle;
    y.labelingPolicy = CPTAxisLabelingPolicyNone;
    y.labelTextStyle = axisTextStyle;
    y.labelOffset = -16.0f;
    y.majorTickLineStyle = axisLineStyle;
    y.majorTickLength = 2.0f;
    y.minorTickLength = 2.0f;

    NSInteger majorIncrement = 10;
    NSInteger minorIncrement = 1;
    CGFloat yMax = 40.0f; // should determine dynamically based on max temp
    NSMutableSet *yLabels = [NSMutableSet set];
    NSMutableSet *yMajorLocations = [NSMutableSet set];
    NSMutableSet *yMinorLocations = [NSMutableSet set];
    for (NSInteger j = minorIncrement; j <= yMax; j+= minorIncrement)
    {
        NSInteger mod = j % majorIncrement;
        if (mod == 0)
        {
            CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:@"%li", (long)j] textStyle:y.labelTextStyle];
            NSDecimal location = CPTDecimalFromInteger(j);
            label.tickLocation = location;
            label.offset = -y.majorTickLength - y.labelOffset;
            if (label)
            {
                [yLabels addObject:label];
            }
            [yMajorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:location]];
        }
        else
        {
            [yMinorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:CPTDecimalFromInteger(j)]];
        }
    }
    y.axisLabels = yLabels;
    y.majorTickLocations = yMajorLocations;
    y.minorTickLocations = yMinorLocations;

    CPTGraph *graph = self.hostView.hostedGraph;
    graph.legend = [CPTLegend legendWithGraph:graph];
    CPTMutableLineStyle *legendBorderlineStyle = [CPTMutableLineStyle lineStyle];
    legendBorderlineStyle.lineColor = [CPTColor blackColor];
    legendBorderlineStyle.lineWidth = 1.0f;
    legendBorderlineStyle.lineColor = [CPTColor blackColor];
    graph.legend.borderLineStyle = legendBorderlineStyle;
    graph.legend.fill = [CPTFill fillWithColor:[CPTColor lightGrayColor]];
    graph.legend.cornerRadius = 5.0;
    graph.legend.swatchSize = CGSizeMake(10, 20);
    graph.legendAnchor = CPTRectAnchorBottom;
    graph.legend.textStyle = axisTextStyle;
    graph.legendDisplacement = CGPointMake(150.40, 250.0);   
}
- (NSString *) localTime:(NSString *)time //this is for recount TimeZone ofset
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    //Special Locale for fixed dateStrings
    NSLocale *locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"];
    [formatter setLocale:locale];

    //Assuming the dateString is in GMT+00:00
    //formatter by default would be set to local timezone
    NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

    NSDate *date =[formatter dateFromString:time];

    //After forming the date set local time zone to formatter
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:localTimeZone];

    NSString *newTimeZoneDateString = [formatter stringFromDate:date];

    return newTimeZoneDateString;
}
#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
   // return [DateTime count];
    if ([(NSString *)plot.identifier isEqualToString:@"Temp1"])
    {
        return temp1.count;
    }
    else if ([(NSString *)plot.identifier isEqualToString:@"Temp2"])
    {
        return temp2.count;
    }
    return 0;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{

    NSNumber *num = nil;
    switch (fieldEnum) {
        case CPTScatterPlotFieldX:
            num = [NSNumber numberWithUnsignedInteger:idx];
            break;
        case CPTScatterPlotFieldY:
            if ([(NSString *)plot.identifier isEqualToString:@"Temp1"])
            {
                num = [temp1 objectAtIndex:idx];
            }
            else if ([(NSString *)plot.identifier isEqualToString:@"Temp2"])
            {
                num = [temp2 objectAtIndex:idx];
            }
            break;
    }
    return num;
}

我想要 X 轴上日期时间项之间的比例间隔。如果有人帮助我,我会很幸运。谢谢。 :)

最佳答案

Eric 是专家,他的回答足够好。但我想提供更多细节,这对于像我这样的初学者来说是必要的,因为在将东西放在适当的位置时遇到很多麻烦。

首先,您需要设置适当的范围(我确实从 Eric 那里学到了很多东西)。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:25200]];

NSTimeInterval xLow   = [[dateFormatter dateFromString:@"8:30"] timeIntervalSince1970];
NSTimeInterval xHigh  = [[dateFormatter dateFromString:@"12:00"] timeIntervalSince1970];
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(xLow)
                                               length:CPTDecimalFromDouble(xHigh-xLow)];

接下来,对于固定间隔(例如半小时),使用以下内容:

x.labelingPolicy = CPTAxisLabelingPolicyFixedInterval;
NSTimeInterval x1   = [[dateFormatter dateFromString:@"8:30"] timeIntervalSince1970];
NSTimeInterval x2  = [[dateFormatter dateFromString:@"9:30"] timeIntervalSince1970];
x.majorIntervalLength = CPTDecimalFromDouble(x2-x1);

//Label time Format:
CPTTimeFormatter *timeFormatter = [[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter];
x.labelFormatter   = timeFormatter;

对于自定义标签,将上面两部分替换为以下内容:

x.labelingPolicy = CPTAxisLabelingPolicyNone;
NSMutableSet *xLabels = [NSMutableSet setWithCapacity:[self.arrXValues count]];
NSMutableSet *xLocations = [NSMutableSet setWithCapacity:[self.arrXValues count]];
for (NSString *string in self.arrXValues) {
    CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:string  textStyle:axisTextStyle];
    NSDate *time = [dateFormatter dateFromString:string];
    NSTimeInterval interval = [time timeIntervalSince1970];
    label.tickLocation = CPTDecimalFromDouble(interval);
    label.rotation    = M_PI * 1/4;
    label.offset = 0.0f;
    if (label) {
        [xLabels addObject:label];
        [xLocations addObject:[NSString stringWithFormat:@"%f", interval]];
    }
}
x.axisLabels = xLabels;
x.majorTickLocations = xLocations;

最后,核心情节委托(delegate)方法,

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)indexPath
{
if(fieldEnum == CPTScatterPlotFieldX)
{
    //return [NSNumber numberWithFloat:[[self.arrXValues objectAtIndex:indexPath] floatValue]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:25200]];
    NSDate *time = [dateFormatter dateFromString:[self.arrXValues objectAtIndex:indexPath]];
    NSTimeInterval interval = [time timeIntervalSince1970];

    return [NSNumber numberWithDouble:interval];
}
else if(fieldEnum == CPTScatterPlotFieldY) {
    return [NSNumber numberWithFloat:[[self.arrYValues objectAtIndex:indexPath] floatValue]];
}
return nil;
}

关于iOS CorePlot x 轴 DateTime 间隔成比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23495402/

有关iOS CorePlot x 轴 DateTime 间隔成比例的更多相关文章

  1. ruby-on-rails - Rails 3 I18 : translation missing: da. datetime.distance_in_words.about_x_hours - 2

    我看到这个错误:translationmissing:da.datetime.distance_in_words.about_x_hours我的语言环境文件:http://pastie.org/2944890我的看法:我已将其添加到我的application.rb中:config.i18n.load_path+=Dir[Rails.root.join('my','locales','*.{rb,yml}').to_s]config.i18n.default_locale=:da如果我删除I18配置,帮助程序会处理英语。更新:我在config/enviorments/devolpment

  2. ruby-on-rails - Rails 2.3.11 DateTime BigDecimal 精度 - 2

    我目前有一个运行Ruby1.8.7和Rails2.3.2的RubyonRails项目我有一些从数据库中读取数据的单元测试,特别是两个连续项目的日期时间列,这两个项目应该相隔24小时。在一项测试中,我将项目2的日期时间设置为与项目1的日期时间相同。当我执行断言以确保两个值相等时,测试在rails2.3.2下工作正常。当我升级到rails2.3.11时,测试失败显示两次之间的差异将关闭并出现以下错误:expectedbutwas.这两个版本的rails中似乎存在浮点转换问题。如何解决float问题? 最佳答案 这也发生在我身上,我最终这

  3. ruby - Rails 比较 date.end_of_day.to_datetime 和 date.to_datetime.end_of_day 返回的日期对象值时返回 false - 2

    ruby1.9.3dev(2011-09-23修订版33323)[i686-linux]轨道3.0.20最近为什么在与DateTimeonRails相关的RSpecs项目上工作我发现在给定日期以下语句发出的值date.end_of_day.to_datetime和date.to_datetime.end_of_day虽然它们表示相同的日期时间,但比较时返回false。为了确认这一点,我打开了Rails控制台并尝试了以下操作1.9.3dev:053>monday=Time.now.monday=>2013-02-2500:00:00+05301.9.3dev:054>monday.cla

  4. ruby - `DateTime.strptime` 返回工作日/时间字符串的无效日期 - 2

    为什么Ruby的strptime不将其转换为DateTime对象:DateTime.strptime('Monday10:20:20','%A%H:%M:%S')#=>ArgumentError:invaliddate虽然这些有效?DateTime.strptime('Wednesday','%A')#=>#DateTime.strptime('10:20:20','%H:%M:%S')#=># 最佳答案 这看起来像一个错误-minitech'scomment是正确的。不过,现在有一个解决方法(因为您可能希望它现在起作用):您可以在

  5. ruby - 如何在 Ruby 中使用 DateTime strptime 解析非英语日期? - 2

    我正在尝试解析从CMS导出的日期。不幸的是,瑞典语言环境设置。月份名称缩写为三个字符,这在May和October月份时有所不同(“maj”与“May”以及“okt”与“Oct”)。我希望使用具有正确区域设置的DateTime.strptime来解决这个问题,如下所示:require'locale'Locale.default="sv_SE"require'date'DateTime.strptime("10okt200904:32",'%d%b%Y%H:%M')然而,日期仍然被解析,因为它会使用英文缩写的月份名称:ArgumentError:invaliddatefromlib/rub

  6. ruby - DateTime 解析未按预期工作 - 2

    我的Ruby代码看起来像这样。str=2010-12-02_12-10-26putsstrputsDateTime.parse(str,"%Y-%m-%d_%H-%M-%S")我希望从解析中得到实际时间。相反,我得到这样的输出......2010-12-02_12-10-262010-12-02T00:00:00+00:00我如何获得解析的时间? 最佳答案 这个有效:str="2010-12-02_12-10-26"putsstrputsDateTime.strptime(str,"%Y-%m-%d_%H-%M-%S")这个例子在C

  7. ruby-on-rails - 如何获得 DateTime 持续时间? - 2

    我很困惑如何做到这一点。我需要获取一个日期时间对象,并获取当前时间的持续时间(以小时、天等为单位)。谢谢。 最佳答案 获取以秒为单位的持续时间很容易:>>foo=Time.new=>MonDec2918:23:51+01002008>>bar=Time.new=>MonDec2918:23:56+01002008>>printbar-foo5.104063=>nil所以,五秒多一点。但要以更人性化的形式呈现它,您需要第三方添加,例如time_period_to_s,或Duration包。

  8. ruby-on-rails - Rails 将 DateTime 转换为 'where' 查询中的日期 - 2

    我需要查询数据库并按开始日期过滤事件,但列类型是DateTime。我在模型中做了范围:scope:day,->(start_date){wherestart_date:start_date}对于相同的DateTime值,它工作正常,但我需要一个过滤器来仅按日期而不是DateTime获取Event。我有PG数据库并尝试:scope:day,->(start_date){where("start_date:date=?","#{start_date.to_date}")}但是我得到一个错误 最佳答案 你可以这样做:使用SQL日期函数(取

  9. ruby - ruby Date.today 和 DateTime.now 的日期错误 - 2

    我已经使用RVM安装了ruby​​-1.8.6-p383。系统ruby是1.9.1_p378-1我在使用ruby​​1.8时从Date.today和DateTime.now得到错误的日期。而Time.now是正确的:irb(main):002:0>DateTime.now.to_s=>"2126--1-10618T11:23:43+00:00"irb(main):004:0>Date.today.to_s=>"2126--1-10618"irb(main):005:0>Time.now=>ThuJan2811:55:27+00002010如果我切换到ruby​​1.9,一切都很好:ir

  10. ruby - 创建具有均匀间隔值的数组 - 2

    生成具有固定距离的值的数组的简单方法是什么?例如:1,4,7,10,...etc我需要能够设置开始、结束和步距。 最佳答案 尝试使用Range.step:>(1..19).step(3).to_a=>[1,4,7,10,13,16,19] 关于ruby-创建具有均匀间隔值的数组,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4838381/

随机推荐