Chartist插件数据点为条形图

时间:2015-10-16 15:23:48

标签: plugins charts chartist.js

我试图让数据指向条形图工作,我找到了折线图的插件,但是不能让它适用于酒吧,任何人都可以帮忙吗?数据点应显示在条形图上方。 https://jsfiddle.net/x79b1m2w/1/

<div class="ct-chart ct-golden-section" id="chart1"></div>
<div class="ct-chart ct-golden-section" id="chart2"></div>

<script>
new Chartist.Bar('#chart1', {
  labels: ['M', 'T', 'W', 'T', 'F'],
  series: [8, 19, 24, 37, 12]
}, {
  distributeSeries: true  
});

new Chartist.Line('#chart2', {
  labels: ['M', 'T', 'W', 'T', 'F'],
  series: [
    [12, 9, 7, 8, 5]
  ]
}, {
  plugins: [
    Chartist.plugins.ctPointLabels({
      textAnchor: 'middle'
    })
  ]
});
</script>
<script>
(function(window, document, Chartist) {
  'use strict';

  var defaultOptions = {
    labelClass: 'ct-label',
    labelOffset: {
      x: 0,
      y: -10
    },
    textAnchor: 'middle',
    labelInterpolationFnc: Chartist.noop
  };

  Chartist.plugins = Chartist.plugins || {};
  Chartist.plugins.ctPointLabels = function(options) {

    options = Chartist.extend({}, defaultOptions, options);

    return function ctPointLabels(chart) {
      if(chart instanceof Chartist.Line) {
        chart.on('draw', function(data) {
          if(data.type === 'point') {
            data.group.elem('text', {
              x: data.x + options.labelOffset.x,
              y: data.y + options.labelOffset.y,
              style: 'text-anchor: ' + options.textAnchor
            }, options.labelClass).text(options.labelInterpolationFnc(data.value.x === undefined ? data.value.y : data.value.x + ', ' + data.value.y));
          }
        });
      }
            if(chart instanceof Chartist.Bar) {
        chart.on('draw', function(data) {
          if(data.type === 'bar') {
            data.group.elem('text', {
              x: data.x + options.labelOffset.x,
              y: data.y + options.labelOffset.y,
              style: 'text-anchor: ' + options.textAnchor
            }, options.labelClass).text(options.labelInterpolationFnc(data.value.x === undefined ? data.value.y : data.value.x + ', ' + data.value.y));
          }
        });
      }
    };
  };

}(window, document, Chartist));

2 个答案:

答案 0 :(得分:0)

将您的插件代码更改为:

import UIKit
import ActionSheetPicker_3_0

class SearchController: UIViewController, NSXMLParserDelegate, UISearchBarDelegate , UITableViewDelegate , UITableViewDataSource {


    @IBOutlet weak var selectDepartmentView: UIButton!
    @IBOutlet weak var selectDoctorView: UIButton!

    var parser = NSXMLParser()
    var posts = NSMutableArray()
    var DoctorArray = NSMutableArray()
    var DepartmentArray = NSMutableArray()
    var DoctorArrayAsDepartment = NSMutableArray()
    var elements = NSMutableDictionary()
    var element = NSString()
    var nsArray = NSMutableString()
    var nsArray2 = NSMutableString()
    var PickValue=""
    //=======search bar============
    var searchActive : Bool = false
    var filtered:[String] = []
    //======search Bar===============
    var nonMutableArray:[String] = []

    @IBOutlet weak var searchBar: UISearchBar!

    @IBOutlet weak var tableView: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()

        // self.GetDeartmentsListParsing()
        self.GetDocotorListParsing()


        // Do any additional setup after loading the view.
        searchBar.delegate = self
        tableView.delegate = self
        tableView.dataSource = self

        tableView.tableFooterView = UIView(frame: CGRectZero)
    }


    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        searchActive = true;
    }

    func searchBarTextDidEndEditing(searchBar: UISearchBar) {
        searchActive = false;
    }

    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        searchActive = false;
    }

    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        searchActive = false;
    }

    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

        filtered = nonMutableArray.filter({ (text) -> Bool in
            let tmp: NSString = text
            let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
            return range.location != NSNotFound
        })
        if(filtered.count == 0){
            searchActive = false;
        } else {
            searchActive = true;
        }
        self.tableView.reloadData()
        println("searchText:" + searchText)
       // searchBar.text = filtered[indexPath.row]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if(searchActive) {
            return filtered.count
        }
        return nonMutableArray.count;
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell;
        if(searchActive){
            cell.textLabel?.text = filtered[indexPath.row]
        } else {
            cell.textLabel?.text = nil
           // nonMutableArray.removeAll()
        }

        return cell;
    }


    func GetDocotorListParsing()
    {
        posts = []
        parser = NSXMLParser(contentsOfURL:(NSURL(string:"http://13.192.12.86:201/Api_interfaceTest.aspx?opname=something&PassKey=xyz")))
        parser.delegate = self
        parser.parse()

        println("into GetDoctorListParsing")
    }


    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
    {
        element = elementName
        if (elementName as NSString).isEqualToString("ReturnTable")
        {
            elements = NSMutableDictionary()
            elements = [:]

             nsArray = NSMutableString()
             nsArray = ""

             nsArray2 = NSMutableString()
             nsArray2 = ""
        }
    }

    func parser(parser: NSXMLParser!, foundCharacters string: String!)
    {

        if element.isEqualToString("Departmentname") {
            nsArray.appendString(string) // nsArray is NSMutableString
        }
       else if element.isEqualToString("PersonFullName") {
            nsArray2.appendString(string)

        }

    }

    func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!)
    {
        if (elementName as NSString).isEqualToString("Departmentname") {
            if !nsArray.isEqual(nil) {
                elements.setObject(nsArray, forKey: "DepartmentName")

            }
            if !nsArray2.isEqual(nil) {
                elements.setObject(nsArray2, forKey: "DoctorName")
            }
            posts.addObject(elements)
          // ===== This is the posts array i gave output above ===

            let myArrayDepartment = (posts.valueForKey("DepartmentName") as? [String])
            DepartmentArray = NSMutableArray(array: myArrayDepartment!)
            println(DepartmentArray)


            let myArrayDoctor = posts.valueForKey("DoctorName") as? [String]
            DoctorArray = NSMutableArray(array: myArrayDoctor!)
            println(DoctorArray)
            nonMutableArray = DoctorArray as AnyObject as [String]

        }
            }

    @IBAction func SelectDoctorButton(sender: AnyObject) {

                    // Inside a IBAction method:
                // Create an array of strings you want to show in the picker:
        searchActive = false;
        ActionSheetMultipleStringPicker.showPickerWithTitle("Select Department", rows: [
            DepartmentArray], initialSelection: [1], doneBlock: {
                picker, values, indexes in

                print("values = \(values)")
                print("indexes = \(indexes)")
                print("picker = \(picker)")

                var firstValue: AnyObject! = indexes[0]

                self.PickValue = firstValue as String

               self.selectDepartmentView.setTitle(firstValue as? String, forState: UIControlState.Normal)

                for var i=0 ; i<10 ; i++ {
                    let indexes = (self.posts.valueForKey("DepartmentName"))?.indexOfObject(self.PickValue)
                    // println("@@@@@sucess@@@@" +  index)
                    NSLog("\(indexes)")
                    //  find(posts.valueForKey("DepartmentName")),"")

                }

                return

            }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: sender)

        // You can also use self.view if you don't have a sender

    }

    @IBAction func SelectDoctor(sender: AnyObject) {

         tableView.reloadData()
         searchActive = false;

        ActionSheetMultipleStringPicker.showPickerWithTitle("Select Doctor", rows: [
            DoctorArray,

            ], initialSelection: [1, 1], doneBlock: {
                picker, values, indexes in

                print("values = \(values)")
                print("indexes = \(indexes)")
                print("picker = \(picker)")

                var firstValue: AnyObject! = indexes[0]

                self.PickValue = firstValue as String
                  self.selectDoctorView.setTitle(firstValue as? String, forState: UIControlState.Normal)
                return
            }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: sender)


    }

    // Build in Methode
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

        self.view.endEditing(true)

        }
}

答案 1 :(得分:0)

有一个插件可以为条形图和柱形图添加标签。

见这里:https://github.com/YorkshireInteractive/chartist-bar-labels

然后我从以下github评论中借用了标签位置计算:

https://github.com/gionkunz/chartist-js/issues/281

简而言之,我在ctBarLabels插件选项中有以下内容:

            position: {
            x: function(data) {
                return data.x1 + (data.element.width() * .5);
            },
            y: function(data) {
                return data.y1 + (data.element.height() * -1) - 10;
            }

我现在可以使用样式表为标签设置样式。我还可以使用函数来格式化标签(例如,货币与普通值)。