GithubHelp home page GithubHelp logo

swift-linechart's Introduction

Swift LineChart

line chart demo

Usage

var lineChart = LineChart()
lineChart.addLine([3, 4, 9, 11, 13, 15])

Features

  • Super simple
  • Highly customizable
  • Auto scaling
  • Touch enabled
  • Area below lines

Properties

Both x and y properties are of type Coordinate. Each can be customized separately and has its own settings for labels, gridlines and axis.

  • labels: Labels
  • grid: Grid
  • axis: Axis

Labels can be switched on and off and they can have custom values.

  • visible: Bool = true
  • values: [String] = []

Grid can also be switched on/off, has a custom color and you can specify how many gridlines you'd like to show.

  • visible: Bool = true
  • count: CGFloat = 10
  • color: UIColor = UIColor(red: 238/255.0, green: 238/255.0, blue: 238/255.0, alpha: 1) // #eeeeee

Axis can be switched on/off, has a property to its color and you can specify how much the axis is inset from the border of your UIView.

  • visible: Bool = true
  • color: UIColor = UIColor(red: 96/255.0, green: 125/255.0, blue: 139/255.0, alpha: 1) // 607d8b
  • inset: CGFloat = 15

Animations can be customized through the Animation settings.

  • enabled: Bool = true
  • duration: CFTimeInterval = 1

If you'd like to show extra dots at your data points use the Dots features.

  • visible: Bool = true
  • color: UIColor = UIColor.whiteColor()
  • innerRadius: CGFloat = 8
  • outerRadius: CGFloat = 12
  • innerRadiusHighlighted: CGFloat = 8
  • outerRadiusHighlighted: CGFloat = 12

In addition to the above mentioned features you can further customize your chart.

  • area: Bool = true - Fill the area between line and x axis
  • lineWidth: CGFloat = 2 - Set the line width
  • colors: [UIColor] = [...] - Colors for your line charts

Methods

Add line to chart.

lineChart.addLine(data: [CGFloat])

Remove charts, areas and labels but keep axis and grid.

lineChart.clear()

Make whole UIView white again

lineChart.clearAll()

Delegates

didSelectDataPoint()

Touch event happened at or close to data point.

func didSelectDataPoint(x: CGFloat, yValues: [CGFloat]) {
  println("\(x) and \(yValues)")
}

Examples

Single line with default settings.

line chart demo

var lineChart = LineChart()
lineChart.addLine([3, 4, 9, 11, 13, 15])

Two lines without grid and dots.

two lines without grid and dots

var lineChart = LineChart()
lineChart.area = false
lineChart.x.grid.visible = false
lineChart.x.labels.visible = false
lineChart.y.grid.visible = false
lineChart.y.labels.visible = false
lineChart.dots.visible = false
lineChart.addLine([3, 4, 9, 11, 13, 15])
lineChart.addLine([5, 4, 3, 6, 6, 7])

Show x and y axis

chart with x and y axis

var lineChart = LineChart()
lineChart.area = false
lineChart.x.grid.count = 5
lineChart.y.grid.count = 5
lineChart.addLine([3, 4, 9, 11, 13, 15])
lineChart.addLine([5, 4, 3, 6, 6, 7])

License

MIT

swift-linechart's People

Contributors

zemirco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swift-linechart's Issues

APIs deprecated as of iOS 7 and earlier are unavailable in Swift

Hi Zemirco,
i've follow your instructions for install LineCharts into my project.
But when i put LineChart.swift into my project at line path = layer.path i've this error:

LineChart.swift:799:26: 'path' is unavailable: APIs deprecated as of iOS 7 and earlier are unavailable in Swift

Can i solve it?

Thanks and Regards

Y-Axis-Labels doesn't doesn't show max value, and can't determine values manually

I'm drawing the line-Charts shown below.

However, the y-values are not very useful in light of my dataset: lineChart.addLine([0, -2, 1, 7, 9])

It shows 0 and 5? In this case, the logical numbers to show would be -2, 0 and 9

img_0066_2

(To make it only show 2 numbers. I had to decrease the grid size with: lineChart.y.grid.count = 3)
What I was hoping to happen is to see 3 numbers. Not 2...

I also tried changing it to 4, but the numbers are way to close together, and it still only goes up to "8" not 9, making the chart more misleading than the last one.

If I don't specify the y.grid.count at all. There's way too many y labels overlapping each other.

I tried adding the values manually with: lineChart.y.labels.values = ["-2","0","9"]
but that does nothing at all?

Also enhancement ideas.

Make the x axis, the lowest number in the array. (it's hardcoded to 0 right now), I had to change it manually to make it work for me.

Add an optional line at 0, and make an option for dashing it.

Make the font,size and color of the labels customisable.

Y Axis [ Min / Max ]

  • Is there a way to get the data for the Y-Axis to start from a certain number in the dataset ?
  • Currently it's just starting from 0 making large numbers essentially a flat horizontal line at the top of the chart.
  • I tried adjusting various draw parts of the code with a getMinimumValue func but it still didn't work.

func getMinimumValue() -> CGFloat {
var minimum = Int.max
for data in dataStore {
var newMin = data.reduce(Int.max, { min(Int($0), Int($1)) })
if newMin < minimum {
minimum = newMin
}
}
return CGFloat(minimum)
}

Constraints distort chart

When i try to center the chart and add a vertical constraint it distorts the chart.

ios simulator screen shot sep 4 2014 3 18 42 pm

    var views: Dictionary<String, AnyObject> = [:]

    var data: Array<CGFloat> = [100, 100, 100]
    var data2: Array<CGFloat> = [1000, 1000, 1010]
    var data3: Array<CGFloat> = [225, 400]

    lineChart = LineChart()
    lineChart!.addLine(data)
    lineChart!.addLine(data2)
    lineChart!.addLine(data3)
    lineChart!.dotsVisible = true
    lineChart!.gridVisible = false
    lineChart!.axisInset = 40
    lineChart!.labelsYVisible = true
    lineChart!.setTranslatesAutoresizingMaskIntoConstraints(false)
    lineChart!.delegate = self
    self.view.addSubview(lineChart!)
    views["chart"] = lineChart
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[chart(300)]", options: nil, metrics: nil, views: views))
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-320-[chart(200)]", options: nil, metrics: nil, views: views))

How to adjust the scale of the y-axis?

Hi, thanks for making this framework.
Wondering if there is a way to adjust the scaling of the y-axis.
I believe i read in the documentation that the linechart automatically handles scaling the height of the y-axis but that doesn't seem to be the case as can be seen in the attached screenshot. In the image below there are about the first value is at coordinates (x=0, y=17) which makes sense if each line of the grid is 10 units.

Any advice?

Thank you.

screen shot 2018-08-15 at 11 06 27 am

Android Equivalent for this line chart

Hello Zemirco,

I have used swift linechart sdk for my iPhone native app now i need to use this for my android native app but i am not getting any reference for this, can you please help me for this.

Thanks
Vivek Dharmani

1 data point

I am getting

Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan 30]'

when i try to draw a chart with only 1 point on it.

 func drawDataDots(xAxis: Array<CGFloat>, yAxis: Array<CGFloat>, lineIndex: Int) {
    var dots: Array<DotCALayer> = []
    for index in 0..<xAxis.count {
        var xValue = xAxis[index] + axisInset - outerRadius/2
        var yValue = self.bounds.height - yAxis[index] - axisInset - outerRadius/2

        // draw custom layer with another layer in the center
        var dotLayer = DotCALayer()
        dotLayer.dotInnerColor = colors[lineIndex]
        dotLayer.innerRadius = innerRadius
        dotLayer.backgroundColor = dotsBackgroundColor.CGColor
        dotLayer.cornerRadius = outerRadius / 2
        dotLayer.frame = CGRect(x: xValue, y: yValue, width: outerRadius, height: outerRadius) 
        self.layer.addSublayer(dotLayer)
        dots.append(dotLayer)

        // animate opacity
        if animationEnabled {
            var animation = CABasicAnimation(keyPath: "opacity")
            animation.duration = animationDuration
            animation.fromValue = 0
            animation.toValue = 1
            dotLayer.addAnimation(animation, forKey: "opacity")
        }

    }
    dotsDataStore.append(dots)
}

dotLayer.frame = CGRect(x: xValue, y: yValue, width: outerRadius, height: outerRadius)
is the line throwing the error

String as labels

You should allow strings as labels. In example addLine([("mystring", 5), ("myotherstring", 6)])

Multiple y-axis

Hello, is it posible to have different y-axis to every line?

How to clear lines and dots

When I use open func clear(), I get an index out of bound error on the first line of fileprivate var drawingWidth.
What is the best way to clear just the lines and the dots, but keep the axis and labels?

Chart doesn't use entire UIView area

I'm trying to create a line graph similar to the one Robinhood uses:

But when I remove the axises and set their insets to 0 it still seems to have padding. Any idea what is going on?

img_0146

colors array not initialized when using nib/storyboard

When using nib or storyboard to create custom view with class 'LineChart', then only "init(coder aDecoder: NSCoder)" is called, not "init(frame: CGRect)". This means the initialization code for "self.colors" is never called and app will crash during "drawLine" at "layer.strokeColor = colors[lineIndex].CGColor"

Request help or option for (x-axis, y-axis) data pairs

Hi. Really like swift-linechart!

It seems that the current version simply uses the y-axis data point numbers as the x-axis elements, i.e., if there are 10 elements in the [y-axis] data array to be plotted, the x-axis numbers range from 0 to 9. However, I'm trying to plot data for (x-axis, y-axis) data pairs, e.g., (2, 7), (5, 12), (10, 16), ... etc., which are in 2 separate files, e.g. x = [2, 5, 10, ...] and y = [7, 12, 16, ...] , so I can't use swift-linechart in its current form.

I'm having difficulty trying to understand your existing code, so that I can modify it to suit my needs. Please modify the code to give an [x-axis] [y-axis] plotting option, or help me understand what needs to be modified so that I can make the necessary changes.

Thanks,
Doug

Assigning lineChart Class to View

having issue when assigning lineChart Class to View and then using it as a outlet,the method didset is called automatically.

Please guide.

Can't add graphs from storyboard

Hello,
I've been experimenting with your Swift files to create a graph on an existing UIView layer, but can't seem to get it to work.

I tried to adding the lines of the graph during viewWillLayoutSubviews, but I keep getting error on:

layer.strokeColor = colors[lineIndex].CGColor

in drawLine() in LineChart.swift file.

"fatal error: Cannot index empty buffer"

Is there any other way that I can plot graphs without having to initialise a LineChart instance manually?

Punkt zu Punkt abstand

Hey Mirco,
Erstmal muss ich sagen das du einen super Graphen in Swift programmiert hast! Mein Problem ist jedoch das es im moment nur die Möglichkeit gibt die Y Achsen Verschiebung der unterschiedlichen Punkte zu bestimmen. Ich würde beispielsweise gerne einen Punkt erstellen mit X = 2.4 und Y = 1.6 leider ist bei deinem Graphen nur ein Punkt X = 1.0 und Y = 1.6 möglich. Das liegt daran das man nur den Y-Abstand durch die Arrays verändern kann, jedoch aber nicht den X-Abstand da dieser auf den wert 1.0 festgelegt ist. Ich hoffe du kannst mir damit helfen!

Mit freundlichen Grüßen Leander Peter

TableView scroll and graph touching not working together

Hello!

Using the library now - it's going great!

But the only problem I have is that I have the chart within a uitableviewcell and when I am scrolling the table, I cant recognize a touch on the graph, and when Im touching the graph, scrolling the tableview doesn't work...

Is there anyway you know of to have them "play nice" with each other?

Thanks

dots

how can i put dots programmatically selected points ?

Scrolling on X axis

Hi,
I need some help with my graph. The main problem is that I have too much value on X-axis and in order to improve UX I'd like to enable scroll on X-axis.
In this way, the user can scroll horizontally the graph (Y-axis must not change).

Thanks for help

Animates only first line after .addLine() invoked

Hello!
When I first time invoke addLine function it works great (line appears with animation), but when I try add second line by invoking the same addLine function, first line appears with animation but second line and other appear without animation.
`@IBAction func addLine(_ sender: UIButton) {

    let data2: [CGFloat] = [1, 3, 5, 13, 17, 20]
    lineChart.colors.append(UIColor.cyan)
    lineChart.addLine(data2) // add second line
    
}
override func viewDidLoad() {
    super.viewDidLoad()
    
    
    label.text = "..."
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textAlignment = NSTextAlignment.center
    self.view.addSubview(label)
    
    // simple arrays
    let data: [CGFloat] = [3, 4, 2, 11, 13, 15]
    
    
    // simple line with custom x axis labels
    let xLabels: [String] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
    
    //lineChart = LineChart()
    lineChart.animation.enabled = true
    lineChart.area = true
    lineChart.x.labels.visible = true
    lineChart.x.grid.count = 10
    lineChart.y.grid.count = 10
    lineChart.x.labels.values = xLabels
    lineChart.y.labels.visible = true
    lineChart.addLine(data) //add first line
    
    lineChart.dots.outerRadius = 6
    lineChart.dots.innerRadius = 4
    
    lineChart.colors = [UIColor.black]
    
    lineChart.translatesAutoresizingMaskIntoConstraints = false
    lineChart.delegate = self
    // Do any additional setup after loading the view, typically from a nib.
}`

Still have 3 errors in example

LineChart.swift:

  1. In:
    // LineChart class
    class LineChart: UIControl {

Error:
LineChart.swift:29:7: Class 'LineChart' does not implement its superclass's required members

  1. In:
    /**
  2. Fill area between charts.
    */
    func drawAreaBetweenLineCharts() {
    . . .
    . . .
    CGContextSetFillColorWithColor(context, positiveAreaColor.CGColor)

Error:
LineChart.swift:459:23: 'ClosedInterval' does not have a member named 'Generator'

DotCALayer.swift:
3. In:
class DotCALayer: CALayer {

Error:
DotCALayer.swift:5:7: Class 'DotCALayer' does not implement its superclass's required members

screenshot at 26 14-01-21

Y Values over 99 show ellipses

Not sure if this is a problem, or if I missed something. But if I try to display data that is greater than 99 then there does not seem to be enough room on the axis to show it. I will have Y values that will be over 10,000. Any suggestions?

Add an horizontal line

Hi, can I insert an horizontal line in the chart? I have a single line chart and I would like to display the medium y-value as a line over the chart. Is it possible?

Story Board Implementation

How can this be implement onto a StoryBoard With a UIView, is there a version of the line chart which has a story board. Please help

How to install to xcode?

I can't find any instructions on how to install this library to Xcode. Please help because it looks amazing and i would love to use it in my new app!

Please, refresh library

Very interesting code, but, unfortunately, it does not work in Xcode 6 Beta 5 - syntax errors…..

Many thanks in advance!

Xcode 7 : Command failed due to signal: Illegal instruction: 4

  1. While emitting SIL for 'bilinear' at /Users/applezone/Desktop/swift-linechart-master/linechart/LineChart.swift:688:13
  2. While emitting SIL for 'f' at /Users/applezone/Desktop/swift-linechart-master/linechart/LineChart.swift:691:9
  3. While verifying SIL function @TFFC9linechart11LinearScaleP33_CD20E833F1FD275E0E122EE071F674AE8bilinearFS0_FTGSaV12CoreGraphics7CGFloat_5rangeGSaS2__13uninterpolateFT1aS2_1bS2__FT1cS2__S2_11interpolateFT1aS2_1bS2__FT1cS2__S2__FT1cS2__S2_L_1ffS2_S2 for 'f' at /Users/applezone/Desktop/swift-linechart-master/linechart/LineChart.swift:691:9

hide grid and axis

is there a way to hide all other views except line graph,
please guide..

Y-Axis label for range > 100 becomes "..." & Missing Argument for parameter 'labels'

Hi,

Issue : 1 I'm trying to integrate swift-linechart with one of my projects (in Xcode 6.2). It's working fine with Xcode 6.3 beta. But when I'm trying with Xcode 6.2 there are some compatibility issues. I resolved most of them but this particular one I'm not able to. When I recreate the same scenario in Playground it works fine. I did checkout your old commits but couldn't resolve the issue

Can you help me with this ?

screen shot 2015-03-20 at 4 04 32 pm

Issue : 2 By default Y- axis label for range after 100 becomes becomes "..."

How to pass X and Y Co-ordinates individually

Is there any way to pass x and y co-ordinates individually, as below.

let data = [(x: 0, y: 0), (x: 0.5, y: 3.1), (x: 1.2, y: 2), (x: 2.1, y: -4.2), (x: 2.6, y: 1.1)]

Please help me.

Highlight a single datapoint

So I've been futzing around with the code for a while now, and I can't seem to figure out how to make this work.

What I'd like to have happen is that I can single out a data point in the chart and have a differently-colored dot drawn at that point. Sort of like when the user clicks on a dot, but drawn at chart creation time. If a user inserts a new value in the chart, that value would be highlighted.

What I tried to do was take the highlightDataPoints method and change it slightly. In fact. all I did was copy the method to a new (public) one called highlightDot(index: Int) and change one line:

dot.backgroundColor = Helpers.lightenUIColor(colors[lineIndex]).CGColor
to
dot.backgroundColor = Helpers.lightenUIColor(colors[lineIndex + 1]).CGColor

At chart-creation time, after the chart is drawn, I call highlightDot() with the index of the data point to be highlighted. Trouble is, this just fails to do anything. In the debugger, I see that when MY method is called, dotsDataStore is empty.

So, clearly I'm missing something fundamental and probably dead-simple.

Anyone able to clear it up for me?

App Crash When adding more data dot line than x-axis value

I face app crash issue when i try to add more data dot line than x-axis value on LineChart.
Thank you for awesome library .

    // simple arrays
    let data: [CGFloat] = [3, 4, 7, 9 ,2 , -2, 11, 13, 15]
    
    // simple line with custom x axis labels
    let xLabels: [String] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]

Ain't y axis values assignable?

So, I am trying to draw a line chart on my app. And I found that somehow I could not assign the values to y axis. But x axis was totally fine. It assumed that the code might automatically generated the values from my data set.

my code is like this below

// simple arrays
let data: [CGFloat] = [3, 4, -2, 11, 13, 15]
let data2: [CGFloat] = [1, 3, 5, 13, 17, 20]

// simple line with custom x axis labels
let xLabels: [String] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
let yLabels: [String] = ["0.1k", "0.2k", "0.3k", "0.4k", "0.5k", "0.6k"]

lineChart = LineChart()
lineChart.animation.enabled = true
lineChart.area = false
lineChart.x.labels.visible = true
lineChart.y.labels.visible = true

lineChart.y.axis.inset = 30
lineChart.x.axis.inset = 30

lineChart.x.grid.count = 5
lineChart.y.grid.count = 6

lineChart.x.labels.values = xLabels
lineChart.y.labels.values = yLabels

lineChart.addLine(data)
lineChart.addLine(data2)

lineChart.translatesAutoresizingMaskIntoConstraints = false
lineChart.delegate = self
chartView.addSubview(lineChart)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.