iOS Core Plot with Swift - Formatting Axis - ios

Hi I am new to core plot and I have this issue and its bugging me for sometime..
The issue is that both X and Y axis won't show the axis label, axis tile, axis majorlengthinterval, etc.. Basically, I cannot set the axis properties except axis line style. The following is my code.
class testVC: UIViewController, CPTPlotDataSource, CPTPlotDelegate, CPTPlotSpaceDelegate {
var hostView: CPTGraphHostingView!
let xData = ["2","4"]
let yData = ["1","2"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func symbolForScatterPlot(aPlot: CPTScatterPlot, recordIndex index: UInt) -> CPTPlotSymbol {
let dotStyle = CPTPlotSymbol()
dotStyle.size = CGSizeMake(6, 6)
dotStyle.fill = CPTFill(color: CPTColor.blueColor())
dotStyle.symbolType = CPTPlotSymbolType.Ellipse
return dotStyle
}
#IBAction func plotClick(sender: AnyObject) {
let frame = self.view.frame
//add graph
let graph = CPTXYGraph(frame: CGRect(x: 0, y: 50, width: frame.width, height: frame.height - 250))
graph.paddingBottom = 10
graph.paddingLeft = 10
graph.paddingRight = 10
graph.paddingTop = 10
graph.title = "Scatter Plot"
//hostView
hostView = CPTGraphHostingView(frame: graph.frame)
self.view.addSubview(hostView)
//add scatter plot and plot space
var scatterPlot = CPTScatterPlot()
scatterPlot = CPTScatterPlot(frame: hostView.frame)
scatterPlot.delegate = self
scatterPlot.dataSource = self
let plotSpace = graph.defaultPlotSpace as! CPTXYPlotSpace
plotSpace.delegate = self
plotSpace.allowsUserInteraction = true
plotSpace.xRange = CPTPlotRange(location: 0, length: 10)
plotSpace.yRange = CPTPlotRange(location: 0, length: 18)
scatterPlot.dataLineStyle = nil //hide line
graph.addPlot(scatterPlot)
//set axis
let axes: CPTXYAxisSet = CPTXYAxisSet(layer: graph.axisSet!); let x = axes.xAxis; let y = axes.yAxis
let lineStyle = CPTMutableLineStyle()
lineStyle.lineWidth = 3
x!.axisLineStyle = lineStyle; y!.axisLineStyle = lineStyle
x!.title = "X"; y!.title = "Y"
x!.orthogonalPosition = 0; y!.orthogonalPosition = 0
x!.majorIntervalLength = 1; y!.majorIntervalLength = 1
x!.minorTickLength = 4; y!.minorTickLength = 4
hostView.hostedGraph = graph
}
func numberOfRecordsForPlot(plot: CPTPlot) -> UInt {
return 2
}
func numberForPlot(plot: CPTPlot, field fieldEnum: UInt, recordIndex idx: UInt) -> AnyObject? {
if fieldEnum == 0 {
return xData[Int(idx)]
} else {
return yData[Int(idx)]
}
}

You're not setting the axis properties on the one belonging to the graph—you're setting up a copy which then goes away. Try this instead:
let axes = graph.axisSet as? CPTXYAxisSet

Related

Change position of data labels to bottom of the line in ios charts

I have used this library on swift called: iOS Charts https://github.com/danielgindi/ios-charts
I have two datasets and I want to set the position of data labels in one of the dataset to the bottom of the line, so the numbers can be visible and no overlapping happens. How can I do this?
I setup the chart as follows:
private func configureChart() {
lineChartView = LineChartView(frame: CGRect(x: 0, y: 60, width: self.view.frame.width, height: 200))
lineChartView?.delegate = self
lineChartView?.chartDescription?.enabled = false
lineChartView?.dragEnabled = true
lineChartView?.setScaleEnabled(false)
lineChartView?.pinchZoomEnabled = false
lineChartView?.rightAxis.enabled = false
lineChartView?.xAxis.valueFormatter = self
lineChartView?.xAxis.granularity = 1
lineChartView?.legend.form = .line
lineChartView?.animate(yAxisDuration: 0.3)
if let lineChartView = lineChartView {
dashboardHeaderView?.subviews.filter({ $0 is LineChartView }).forEach {
$0.removeFromSuperview()
}
dashboardHeaderView?.addSubview(lineChartView)
}
setupLineChartData()
}
func setupLineChartData() {
monthData = ReportModel.monthlyOveralInfo()
let costSet = self.provideLineData(type: .totalCost)
let incomeSet = self.provideLineData(type: .totalIncome)
let lineChartData = LineChartData(dataSets: [incomeSet, costSet])
lineChartView?.data = lineChartData
lineChartView?.setVisibleXRangeMaximum(5)
lineChartView?.moveViewToX(lineChartView?.chartXMax ?? 0)
}
private func provideLineData(type: SWMonthlyOverallType) -> LineChartDataSet {
var mainColor: UIColor = .black
var gradientFirstColor: UIColor = .clear
var gradientSecondColor: UIColor = .black
if type == .totalIncome {
mainColor = .myAppGreen
gradientFirstColor = .clear
gradientSecondColor = .myAppGreen
}
let totalCosts = monthData.compactMap({
$0.items.first(where: {$0.type == type})
})
var index: Double = -1
let values: [ChartDataEntry] = totalCosts.compactMap({
index += 1
return ChartDataEntry(x: index, y: $0.value)
})
let chartDataSet = LineChartDataSet(values: values, label: type.rawValue)
chartDataSet.resetColors()
chartDataSet.drawIconsEnabled = false
chartDataSet.setColor(mainColor)
chartDataSet.setCircleColor(mainColor)
chartDataSet.lineWidth = 1
chartDataSet.circleRadius = 3
chartDataSet.drawCircleHoleEnabled = true
chartDataSet.valueFont = .systemFont(ofSize: 9)
let gradientColors = [gradientFirstColor.cgColor,
gradientSecondColor.cgColor]
let gradient = CGGradient(colorsSpace: nil, colors: gradientColors as CFArray, locations: nil)
chartDataSet.fillAlpha = 0.5
if let gradient = gradient {
chartDataSet.fill = Fill(linearGradient: gradient, angle: 90)
}
chartDataSet.drawFilledEnabled = true
return chartDataSet
}
Just posting in case someone finds it to be useful:
chart.xAxis.labelPosition = .bottom

Only one label appearing on a BarChart created with Charts

I want to create a BarChart with the Charts library. Everything is working good except the labels on the x axis. Only the first label "Jan" is appearing on the line. This is my code
override func viewWillAppear(_ animated: Bool) {
doBarChart()
}
func doBarChart(){
barChartView.drawBarShadowEnabled = false
barChartView.drawValueAboveBarEnabled = true
barChartView.chartDescription?.enabled = false
barChartView.maxVisibleCount = 60
let xAxis = barChartView.xAxis
xAxis.axisLineColor = UIColor.black
xAxis.labelPosition = .bottom
xAxis.drawAxisLineEnabled = true
xAxis.drawGridLinesEnabled = false
xAxis.granularity = 1.0
xAxis.labelCount = 1
// xAxis.setLabelCount(7, force: true)
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",]
xAxis.valueFormatter = IndexAxisValueFormatter(values:months)
//Also, you probably want to add:
let leftAxis = barChartView.leftAxis;
leftAxis.enabled = false
leftAxis.drawAxisLineEnabled = false;
leftAxis.drawGridLinesEnabled = false;
leftAxis.axisMinimum = 0.0; // this replaces startAtZero = YES
let rightAxis = barChartView.rightAxis
rightAxis.enabled = false;
rightAxis.drawAxisLineEnabled = true;
rightAxis.drawGridLinesEnabled = false;
rightAxis.axisMinimum = 0.0; // this replaces startAtZero = YES
let l = barChartView.legend
l.enabled = false
barChartView.fitBars = true;
barChartView.animate(xAxisDuration: 0.2, yAxisDuration: 1.0, easingOptionX: .easeInExpo, easingOptionY: .easeInExpo)
setDataCount(count: 7, range: 50)
}
func setDataCount(count: Int, range: Double){
let barWidth = 7.0
let spaceForBar = 10.0
var yVals = [BarChartDataEntry]()
yVals.append(BarChartDataEntry(x: Double(0) * spaceForBar, y: 44.5))
yVals.append(BarChartDataEntry(x: Double(1) * spaceForBar, y: 78.1))
yVals.append(BarChartDataEntry(x: Double(2) * spaceForBar, y: 50.3))
yVals.append(BarChartDataEntry(x: Double(3) * spaceForBar, y: 56.6))
yVals.append(BarChartDataEntry(x: Double(4) * spaceForBar, y: 20.5))
yVals.append(BarChartDataEntry(x: Double(5) * spaceForBar, y: 44.3))
yVals.append(BarChartDataEntry(x: Double(6) * spaceForBar, y: 54.4))
var set1 : BarChartDataSet!
if let count = barChartView.data?.dataSetCount, count > 0{
set1 = barChartView.data?.dataSets[0] as! BarChartDataSet
set1.values = yVals
set1.colors = [UIColor.black,UIColor.orange,UIColor.red,UIColor.green,UIColor.yellow,UIColor.blue,UIColor.gray]
barChartView.data?.notifyDataChanged()
barChartView.notifyDataSetChanged()
}else{
set1 = BarChartDataSet(values: yVals, label: "DataSet")
set1.colors = [UIColor.black,UIColor.orange,UIColor.red,UIColor.green,UIColor.yellow,UIColor.blue,UIColor.gray]
var dataSets = [BarChartDataSet]()
dataSets.append(set1)
let data = BarChartData(dataSets: dataSets)
data.barWidth = barWidth;
barChartView.data = data
}
}
Add the following delegate method of "IAxisValueFormatter"
And assign these delegate.
class xyz : IAxisValueFormatter{
weak var axisFormatDelegate: IAxisValueFormatter?
//add these line in the func...
func doBarChart{
let xAxisValue = lineChartView.xAxis
xAxisValue.valueFormatter = axisFormatDelegate
lineChartView.xAxis.granularityEnabled = true
lineChartView.xAxis.granularity = 1.0
}
//add these method..
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return yvlaues[Int(value) % yvlaues.count]
}
}

iOS CorePlot point conversion

I am experimenting with Core Plot. I am trying to add a custom "goal" label over the graph at x: 2.0, y: 50.0 - basically label over the y == 50, its in a separate view, which means I need to convert my point from Core Plot to my UIView bounds. I have not found a combination of points conversions from layer/views that works across all iPhones screen sizes. In my pictures below iPhone 6s is the closest.
iPhone 6s+:
iPhone 6s:
iPhone 5s:
My view layout:
Here is my class:
class BarChartViewController: UIViewController, CPTBarPlotDataSource
{
private var barGraph : CPTXYGraph? = nil
#IBOutlet weak var textBox: UILabel!
#IBOutlet weak var graphHostingView: CPTGraphHostingView!
#IBOutlet weak var textBoxView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(false, animated: false)
self.title = "My results"
let newGraph = CPTXYGraph(frame: CGRectZero)
let theme = CPTTheme(named: kCPTPlainWhiteTheme)
newGraph.applyTheme(theme)
let hostingView = graphHostingView
hostingView.hostedGraph = newGraph
if let frameLayer = newGraph.plotAreaFrame
{
// Border
frameLayer.borderLineStyle = nil
frameLayer.cornerRadius = 0.0
frameLayer.masksToBorder = false
// Paddings
newGraph.paddingLeft = 0.0
newGraph.paddingRight = 0.0
newGraph.paddingTop = 0.0
newGraph.paddingBottom = 0.0
frameLayer.paddingLeft = 70.0
frameLayer.paddingTop = 20.0
frameLayer.paddingRight = 20.0
frameLayer.paddingBottom = 80.0
}
// Plot space
let plotSpace = newGraph.defaultPlotSpace as? CPTXYPlotSpace
plotSpace?.yRange = CPTPlotRange(location: 0.0, length: 100.0)
plotSpace?.xRange = CPTPlotRange(location: 0.0, length: 4.0)
let axisSet = newGraph.axisSet as? CPTXYAxisSet
if let x = axisSet?.xAxis {
x.axisLineStyle = nil
x.majorTickLineStyle = nil
x.minorTickLineStyle = nil
x.majorIntervalLength = 5.0
x.orthogonalPosition = 0.0
x.title = "X Axis"
x.titleLocation = 7.5
x.titleOffset = 55.0
// Custom labels
x.labelRotation = CGFloat(M_PI_4)
x.labelingPolicy = .None
let customTickLocations = [0.5, 1.5, 2.5]
let xAxisLabels = ["Label A", "Label B", "Label C"]
var labelLocation = 0
var customLabels = Set<CPTAxisLabel>()
for tickLocation in customTickLocations
{
let newLabel = CPTAxisLabel(text: xAxisLabels[labelLocation], textStyle: x.labelTextStyle)
labelLocation += 1
newLabel.tickLocation = tickLocation
newLabel.offset = x.labelOffset + x.majorTickLength
newLabel.rotation = 0 //CGFloat(M_PI_4)
customLabels.insert(newLabel)
}
x.axisLabels = customLabels
}
if let y = axisSet?.yAxis
{
y.axisLineStyle = nil
y.majorGridLineStyle = CPTMutableLineStyle()
var style = y.majorTickLineStyle?.mutableCopy() as? CPTMutableLineStyle
//style!.lineColor = CPTColor(CGColor: UIColor.blackColor()) //UIColor.blackColor())
style!.lineWidth = 10.0
y.minorGridLineStyle = CPTMutableLineStyle()
style = y.minorTickLineStyle?.mutableCopy() as? CPTMutableLineStyle
//style.lineColor = UIColor.redColor()
style!.lineWidth = 10.0
style!.lineCap = .Round
y.majorTickLength = 10.0
y.majorIntervalLength = 50.0
y.orthogonalPosition = 0.0
y.title = "Y Axis"
y.titleOffset = 45.0
y.titleLocation = 150.0
y.labelRotation = 0
y.labelingPolicy = .None
let customTickLocations = [50, 100]
let yAxisLabels = ["50", "100"]
var labelLocation = 0
var customLabels = Set<CPTAxisLabel>()
for tickLocation in customTickLocations
{
let newLabel = CPTAxisLabel(text: yAxisLabels[labelLocation], textStyle: y.labelTextStyle)
labelLocation += 1
newLabel.tickLocation = tickLocation
newLabel.offset = y.labelOffset + y.majorTickLength
newLabel.rotation = 0 //CGFloat(M_PI_4)
customLabels.insert(newLabel)
}
y.axisLabels = customLabels
var nums = Set<NSNumber>()
nums.insert(NSNumber(double: 50.0))
y.majorTickLocations = nums
}
// First bar plot
let barPlot1 = CPTBarPlot.tubularBarPlotWithColor(CPTColor.yellowColor(), horizontalBars: false)
barPlot1.baseValue = 0.0
barPlot1.dataSource = self
//barPlot1.barOffset = 0.5
barPlot1.identifier = "Bar Plot 1"
let textStyle = CPTMutableTextStyle()
textStyle.color = CPTColor.redColor()
textStyle.fontSize = 10.0
barPlot1.labelTextStyle = textStyle
newGraph.addPlot(barPlot1, toPlotSpace: plotSpace)
self.barGraph = newGraph
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.view.layoutIfNeeded()
let point: [Double] = [2.0, 50.0]
let plotPoint = UnsafeMutablePointer<Double>(point)
var dataPoint = self.barGraph?.defaultPlotSpace?.plotAreaViewPointForDoublePrecisionPlotPoint(plotPoint, numberOfCoordinates: 2)
//dataPoint = graphHostingView.layer.convertPoint(dataPoint!, fromLayer: self.barGraph!.plotAreaFrame!.plotArea)
dataPoint = graphHostingView.layer.convertPoint(dataPoint!, toLayer: graphHostingView.layer.superlayer)
//dataPoint = barGraph?.convertPoint(dataPoint!, fromLayer: graphHostingView.layer)
dataPoint = self.textBoxView.convertPoint(dataPoint!, fromView: graphHostingView)
print(dataPoint!)
for item in (self.textBoxView?.constraints)!
{
if let id = item.identifier
{
if id == "goalX"
{
print(item.constant)
item.constant = CGFloat((dataPoint?.x)!) - item.constant
}
else if id == "goalY"
{
print(item.constant)
item.constant = CGFloat((dataPoint?.y)!) - item.constant
}
}
}
barGraph?.titleDisplacement = CGPoint(x: dataPoint!.x * -1, y: dataPoint!.y * -1)
barGraph?.titlePlotAreaFrameAnchor = .TopLeft
self.textBoxView?.layoutIfNeeded()
}
}
Based on some other questions I have seen about CorePlot I know I need to convert it from CorePlot layer to my new view. I left some of my experiments in viewWillAppear() to see what I have tried. None of the solutions on SO seemed to work and I am new to iOS so probably missing something. Any ideas of what conversions I need to do to get my label to show up properly across all screen sizes?
You're on the right track with the point conversion. This is how I would do it:
// Update layer layout if needed
self.view.layoutIfNeeded()
graphHostingView.layer.layoutIfNeeded()
// Point in data coordinates
let point: [Double] = [2.0, 50.0]
// Data point in plot area layer coordinates
var dataPoint = self.barGraph?.defaultPlotSpace?.plotAreaViewPointForPlotPoint(point)
// Convert data point to graph hosting view coordinates
dataPoint = graphHostingView.layer.convertPoint(dataPoint!, fromLayer: self.barGraph!.plotAreaFrame!.plotArea)
Use this to update the constraints on the text box relative to the graph hosting view.

iOS voice recorder visualization on swift

I want to make visualization on the record like on the original Voice Memo app:
I know I can get the levels
- updateMeters
- peakPowerForChannel:
- averagePowerForChannel:
but how to draw the graphic, should I do it custom? Is there free/paid source I can use?
I was having the same problem. I wanted to create a voice memos clone. Recently, I found a solution and wrote an article about it on medium.
I created a subclass from UIView class and drew the bars with CGRect.
import UIKit
class AudioVisualizerView: UIView {
// Bar width
var barWidth: CGFloat = 4.0
// Indicate that waveform should draw active/inactive state
var active = false {
didSet {
if self.active {
self.color = UIColor.red.cgColor
}
else {
self.color = UIColor.gray.cgColor
}
}
}
// Color for bars
var color = UIColor.gray.cgColor
// Given waveforms
var waveforms: [Int] = Array(repeating: 0, count: 100)
// MARK: - Init
override init (frame : CGRect) {
super.init(frame : frame)
self.backgroundColor = UIColor.clear
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
self.backgroundColor = UIColor.clear
}
// MARK: - Draw bars
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
context.clear(rect)
context.setFillColor(red: 0, green: 0, blue: 0, alpha: 0)
context.fill(rect)
context.setLineWidth(1)
context.setStrokeColor(self.color)
let w = rect.size.width
let h = rect.size.height
let t = Int(w / self.barWidth)
let s = max(0, self.waveforms.count - t)
let m = h / 2
let r = self.barWidth / 2
let x = m - r
var bar: CGFloat = 0
for i in s ..< self.waveforms.count {
var v = h * CGFloat(self.waveforms[i]) / 50.0
if v > x {
v = x
}
else if v < 3 {
v = 3
}
let oneX = bar * self.barWidth
var oneY: CGFloat = 0
let twoX = oneX + r
var twoY: CGFloat = 0
var twoS: CGFloat = 0
var twoE: CGFloat = 0
var twoC: Bool = false
let threeX = twoX + r
let threeY = m
if i % 2 == 1 {
oneY = m - v
twoY = m - v
twoS = -180.degreesToRadians
twoE = 0.degreesToRadians
twoC = false
}
else {
oneY = m + v
twoY = m + v
twoS = 180.degreesToRadians
twoE = 0.degreesToRadians
twoC = true
}
context.move(to: CGPoint(x: oneX, y: m))
context.addLine(to: CGPoint(x: oneX, y: oneY))
context.addArc(center: CGPoint(x: twoX, y: twoY), radius: r, startAngle: twoS, endAngle: twoE, clockwise: twoC)
context.addLine(to: CGPoint(x: threeX, y: threeY))
context.strokePath()
bar += 1
}
}
}
For the recording function, I used installTap instance method to record, monitor, and observe the output of the node.
let inputNode = self.audioEngine.inputNode
guard let format = self.format() else {
return
}
inputNode.installTap(onBus: 0, bufferSize: 1024, format: format) { (buffer, time) in
let level: Float = -50
let length: UInt32 = 1024
buffer.frameLength = length
let channels = UnsafeBufferPointer(start: buffer.floatChannelData, count: Int(buffer.format.channelCount))
var value: Float = 0
vDSP_meamgv(channels[0], 1, &value, vDSP_Length(length))
var average: Float = ((value == 0) ? -100 : 20.0 * log10f(value))
if average > 0 {
average = 0
} else if average < -100 {
average = -100
}
let silent = average < level
let ts = NSDate().timeIntervalSince1970
if ts - self.renderTs > 0.1 {
let floats = UnsafeBufferPointer(start: channels[0], count: Int(buffer.frameLength))
let frame = floats.map({ (f) -> Int in
return Int(f * Float(Int16.max))
})
DispatchQueue.main.async {
let seconds = (ts - self.recordingTs)
self.timeLabel.text = seconds.toTimeString
self.renderTs = ts
let len = self.audioView.waveforms.count
for i in 0 ..< len {
let idx = ((frame.count - 1) * i) / len
let f: Float = sqrt(1.5 * abs(Float(frame[idx])) / Float(Int16.max))
self.audioView.waveforms[i] = min(49, Int(f * 50))
}
self.audioView.active = !silent
self.audioView.setNeedsDisplay()
}
}
Here is the article I wrote, and I hope that you will find what you are looking for:
https://medium.com/flawless-app-stories/how-i-created-apples-voice-memos-clone-b6cd6d65f580
The project is also available on GitHub:
https://github.com/HassanElDesouky/VoiceMemosClone
Please note that I'm still a beginner, and I'm sorry my code doesn't seem that clean!

Core Plot Swift BarPlot tickLocation always zero

I'm trying to make a Bar Chart using core-plot under Swift, i have a problem making custom labels on xAxis, they're always in tickLocation zero.
Maybe someone can help me, this is my code.
import UIKit
class aaa: UIViewController, CPTPlotDataSource{
var items :[NSNumber] = [10,35,18, 20, 50, 5]
#IBOutlet var scrollView: UIScrollView!
#IBOutlet weak var lblTitle: UILabel!
#IBOutlet weak var lblChartName: UILabel!
#IBOutlet weak var vGraph: CPTGraphHostingView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.contentSize = CGSizeMake(320, 568);
var id: Int=general.idListed
lblTitle.text=general.namListed
items = [10, 35, 18, 20, 50, 5]
var CPDBarWidth:CGFloat = 0.25
var CPDBarInitialX:CGFloat = 0.25
var graph = CPTXYGraph(frame: CGRectZero)
graph.plotAreaFrame.masksToBorder = false
graph.paddingBottom = 50.0
graph.paddingLeft = 50.0
graph.paddingTop = 50.0
graph.paddingRight = 50.0
graph.backgroundColor = UIColor.whiteColor().CGColor
var titleStyle = CPTMutableTextStyle()
titleStyle.color = CPTColor.blackColor()
titleStyle.fontName = "Helvetica-Bold"
titleStyle.fontSize = 16.0
var title : NSString = "January 19 - 24, 2015"
graph.title = title
graph.titleTextStyle = titleStyle
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop
graph.titleDisplacement = CGPointMake(0.0, 40.0)
var xMin : Float = 0
var xMax : Float = Float(items.count) + 1
var yMin : Float = 0
var yMax : Float = maxItemsValue(items) + 5
var plotSpace = graph.defaultPlotSpace as CPTXYPlotSpace
var xRange = plotSpace.yRange.mutableCopy() as CPTMutablePlotRange
var yRange = plotSpace.yRange.mutableCopy() as CPTMutablePlotRange
xRange.setLocationFloat(xMin)
xRange.setLengthFloat(xMax)
yRange.setLocationFloat(yMin)
yRange.setLengthFloat(yMax)
plotSpace.xRange = xRange
plotSpace.yRange = yRange
var aaplPlot = CPTBarPlot()
aaplPlot.barsAreHorizontal = false
var barLineStyle = CPTMutableLineStyle()
barLineStyle.lineColor = CPTColor.lightGrayColor()
barLineStyle.lineWidth = 1
aaplPlot.dataSource = self
aaplPlot.delegate = self
aaplPlot.barWidthScale = 1
aaplPlot.barOffsetScale = 1
aaplPlot.lineStyle = barLineStyle
graph.addPlot(aaplPlot)
var axisTitleStyle = CPTMutableTextStyle()
axisTitleStyle.color = CPTColor.redColor()
axisTitleStyle.fontName = "Helvetica-Bold"
axisTitleStyle.fontSize = 12.0
var axisLineStyle = CPTMutableLineStyle()
axisLineStyle.lineWidth = 4.0
axisLineStyle.lineColor = CPTColor.redColor()
var axisSet = CPTXYAxisSet()
graph.axisSet = axisSet
axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyNone
axisSet.xAxis.title = "Days of Week"
axisSet.xAxis.titleTextStyle = axisTitleStyle
axisSet.xAxis.titleOffset = 30.0
axisSet.xAxis.majorTickLength = 4
axisSet.xAxis.minorTickLength = 0
axisSet.xAxis.tickDirection = CPTSignNegative
axisSet.xAxis.axisLineStyle = axisLineStyle
var customLabels : NSMutableArray = NSMutableArray (capacity: items.count)
var tickLocations : NSMutableArray = NSMutableArray (capacity: items.count)
var labels : [String] = ["MON","THU","WEN","THR","FRI","SAT"]
var next : Int = 0
var newLabel : CPTAxisLabel
for item in items {
var xlabel : String = labels[next]
next++;
var tstyle : CPTMutableTextStyle = CPTMutableTextStyle()
tstyle.color = CPTColor.blueColor()
tstyle.fontSize = 10
newLabel = CPTAxisLabel(text: xlabel, textStyle: tstyle);
newLabel.setTickLocationFloat(Float(next))
newLabel.offset = 5
customLabels.addObject(newLabel)
tickLocations.addObject(Float(next))
}
axisSet.xAxis.majorTickLocations = NSSet(array: tickLocations)
axisSet.xAxis.axisLabels = NSSet(array: customLabels)
self.vGraph.hostedGraph = graph
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func maxItemsValue(items :[NSNumber])-> NSNumber{
var max : NSNumber=0
for item in items{
if item.floatValue > max.floatValue {
max = item
}
}
return max
}
func numberOfRecordsForPlot(plot: CPTPlot!) -> UInt {
return UInt(items.count)
}
func numberForPlot(plot: CPTPlot!, field fieldEnum: UInt, recordIndex idx: UInt) -> NSNumber! {
switch (fieldEnum) {
case 0:
if (idx < UInt(items.count)) {
return idx + 1
}
break;
case 1:
return items[Int(idx)]
default:
return 1
}
return 1
}
}
You need to set the tickLocation of each new label.
newLabel.tickLocation = next

Resources