Using 3rd party "charts",the response values as double.How it make to integer format? - ios

Using third party "charts".the input format of values are Double and response also in double.For example, my input is a=12,b=13,c=20,d=25 when it comes in graph showing like a=12.0,b=13.0,c=20.0,d=25.0
here is my code
func updateChartData() {
let skipped = 12
let correct = 13
let wrong = 20
let timedOut = 25
let track = ["Skipped", "Right", "Wrong", "Not Attended"]
let money = [skipped, correct, wrong, timedOut]
var entries = [PieChartDataEntry]()
for (index, value) in money.enumerated() {
let entry = PieChartDataEntry()
entry.y = Double(value)
entry.label = track[index]
entries.append( entry)
}
// 3. chart setup
let set = PieChartDataSet( values: entries, label: "Pie Chart")
// this is custom extension method. Download the code for more details.
var colors: [UIColor] = []
for _ in 0..<money.count {
let red = Double(arc4random_uniform(256))
let green = Double(arc4random_uniform(256))
let blue = Double(arc4random_uniform(256))
let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
colors.append(color)
}
set.colors = colors
let data = PieChartData(dataSet: set)
viewPieCharts.data = data
viewPieCharts.noDataText = "No data available"
// user interaction
viewPieCharts.isUserInteractionEnabled = true
let d = Description()
d.text = "iOSCharts.io"
viewPieCharts.chartDescription = d
viewPieCharts.centerText = "Pie Chart"
viewPieCharts.holeRadiusPercent = 0.5
viewPieCharts.transparentCircleColor = UIColor.clear
}
I want the values without decimal point.

Just insert this code
let format = NumberFormatter()
format.numberStyle = .none
let formatter = DefaultValueFormatter(formatter: format)
data.setValueFormatter(formatter)
after
let data = PieChartData(dataSet: set)

Override IValueFormatter and set it to your PieChartData instance
class MyValueFormatter : IValueFormatter {
func stringForValue(_ value: Double,
entry: ChartDataEntry,
dataSetIndex: Int,
viewPortHandler: ViewPortHandler?) -> String {
return String(format: "%.0f", value)
}
}
data.setValueFormatter(MyValueFormatter())

Related

Ios Swift PieChart

How can I display the legend values in ios pie chart? I was able to get only the non zero values. Can anyone help?
func updateChartData12() {
let chart = PieChartView(frame: self.view.frame)
// 2. generate chart data entries
let track = ["Income", "Expense", "Wallet", "Bank"]
let money = [650, 456.13, 0, 0]
var entries = [PieChartDataEntry]()
for (index, value) in money.enumerated() {
let entry = PieChartDataEntry()
if value != 0 {
entry.y = value
entry.label = track[index]
entries.append( entry)
}
}
// 3. chart setup
let set = PieChartDataSet( values: entries, label: "")
// this is custom extension method. Download the code for more details.
var colors: [UIColor] = []
for _ in 0..<money.count {
let red = Double(arc4random_uniform(256))
let green = Double(arc4random_uniform(256))
let blue = Double(arc4random_uniform(256))
let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
colors.append(color)
}
set.colors = colors
let data = PieChartData(dataSet: set)
chart.data = data
chart.noDataText = "No data available"
// user interaction
let d = Description()
chart.chartDescription = d
chart.centerText = "Pie Chart"
chart.holeRadiusPercent = 0.2
chart.transparentCircleColor = UIColor.clear
self.view.addSubview(chart)
}
I am using this code..But I need to display total y values i.e legend at the bottom
Your pie chart is greater than 100%. The data I have is intended to show a total that is over 100% and That the reason it's not work.
let track = ["Income", "Expense", "Wallet", "Bank"]
let money = [650, 456.13, 0, 0]
So use following money array if it's work fine then you would like to check is there build in method to ensure the sum of percentages in the pie chart is 100%
let money = [65, 35, 0, 0]

swift set image center pie chart

Now I use a pie chart from Charts
I want to add a image to the center of the chart instead of the pie chart.
image
What should I do?
code
func updatePieChart(){
let track = ["", ""]
let money = [65, 45]
var entries = [PieChartDataEntry]()
for (index, value) in money.enumerated() {
let entry = PieChartDataEntry()
entry.y = Double(value)
entry.label = track[index]
entries.append( entry)
}
let set = PieChartDataSet( values: entries, label: "Pie Chart")
var colors: [UIColor] = []
for _ in 0..<money.count {
let red = Double(arc4random_uniform(256))
let green = Double(arc4random_uniform(256))
let blue = Double(arc4random_uniform(256))
let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
colors.append(color)
}
set.colors = colors
let data = PieChartData(dataSet: set)
pieview.data = data
pieview.noDataText = "No data available"
// user interaction
pieview.isUserInteractionEnabled = true
let d = Description()
d.text = "iOSCharts.io"
pieview.chartDescription = d
pieview.centerText = "Pie Chart"
pieview.holeRadiusPercent = 0.9
pieview.transparentCircleColor = UIColor.clear
pieview.holeRadiusPercent = 0.65
pieview.transparentCircleRadiusPercent = 0
pieview.legend.enabled = false
pieview.chartDescription?.enabled = false
Please try this :
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "your image")
let attachmentString = NSAttributedString(attachment: attachment)
let labelImg = NSMutableAttributedString(string: "")
labelImg.append(attachmentString)
pieChartView.centerAttributedText = labelImg
try this instead
#IBOutlet weak var chartView: PieChartView!
#IBOutlet weak var image: UIImageView!
...
image.center = chartView.center

Charts, HorizontalBarChartView, how set values alignment = Center?

Swift 3.1, Charts, Multiple cells in tableView with HorizontalBarChartView.
Is it possible to align the value - centered?
Setup charts data:.
func refreshData() {
guard let item = self.item, !item.tasks.isEmpty else {
return
}
self.titleName.text = item.name
self.leftNameMargin.constant = CGFloat(30 * item.level)
self.titleName.textColor = UIColor(hexString: item.color)
let font = UIFont.systemFont(ofSize: 17.0, weight: UIFontWeightSemibold)
var colors: [UIColor] = []
var yValues: [Double] = []
var count = 0.0
for task in item.tasks {
count += Double(task.count)
yValues.append(Double(task.count))
colors.append(UIColor(hexString: task.valueColor))
}
let suffix = String(format: NSXLocalization.string(forKey: KEY_STR_PERCENT)) //fixes '%' duplication
let formatter = NumberFormatter()
formatter.roundingMode = .floor
formatter.numberStyle = .percent
formatter.positiveSuffix = suffix
formatter.negativeSuffix = suffix
formatter.zeroSymbol = ""
let dataEntry = BarChartDataEntry(x: 0.0, yValues: yValues.map { ($0 / count) })
let dataSet = BarChartDataSet(values: [dataEntry], label: nil)
dataSet.colors = colors
dataSet.valueTextColor = .white
dataSet.barBorderColor = .black
dataSet.barBorderWidth = 1.0
dataSet.drawValuesEnabled = true
dataSet.valueFormatter = DefaultValueFormatter(formatter: formatter)
let data = BarChartData(dataSets: [dataSet])
data.setValueFont(font)
data.setDrawValues(true)
data.highlightEnabled = true
self.chart.data = data
}
I Reviewed all internal methods in the charts, but never found a way to center the y values.

How to format xAxis labels iOS charts

Im implementing a barchart and I've managed to assign the data and labels. However, when i load the barchart, it only shows 3/7 of my labels and I'm not sure why.
the labels show up when i interact with the chart but they go glitchy.
I'm sorry if i haven't explained myself well but i have uploaded a .gif showing my problem.
I really need some help with the formatting of the labels on the xAxis. it would be much appreciated.
Thanks in advance.
gif of problem
i think you have used this library(https://github.com/danielgindi/Charts) ... i have set x-Axis using delegate method of chart
func ChartView()
{
xAxis.drawGridLinesEnabled = false
xAxis.drawLabelsEnabled = true
xAxis.labelPosition = .Bottom
xAxis.axisMinimum = 0.0
xAxis.labelCount = ITEM_COUNT
xAxis.granularity = 1.0
xAxis.valueFormatter = self
self.updateChartData()
}
func updateChartData()
{
self.chartView.data = nil
self.setChartData()
}
func generateLineData() -> LineChartData
{
let d = LineChartData()
let entries = NSMutableArray()
var weightstr = String()
var datestr = String()
entries.addObject(ChartDataEntry(x: Double(index), y: ( Double(dic[setvalue]as! String)!)))
let set = LineChartDataSet(values: entries as? [ChartDataEntry] , label: "X-title")
set.setColor(colorWithHexString("#FE1643"))
set.lineWidth = 2.5
set.setCircleColor( UIColor.whiteColor())
set.circleHoleColor = NSUIColor.greenColor()
set.circleRadius = 5.0
set.circleHoleRadius = 2.5
set.fillColor = UIColor.redColor()
set.mode = .HorizontalBezier
set.valueTextColor = UIColor.lightGrayColor()
set.drawValuesEnabled = true
set.valueFont = UIFont(name: "Exo-Regular", size: FOntSIZE(10.0))!
set.axisDependency = .Left
d.addDataSet(set)
return d
}
func setChartData()
{
let data = CombinedChartData()
data.lineData = self.generateLineData()
self.chartView.xAxis.axisMaximum = Double(months.count)-1
self.chartView.data = data
}
func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight)
{
print("chartValueSelected")
}
func chartValueNothingSelected(chartView: ChartViewBase)
{
print("chartValueNothingSelected")
}
func stringForValue(value: Double, axis: AxisBase?) -> String
{
return months[Int(round(value)) % months.count] as! String
}

ios-charts PieChart's label (legends) missing

I am trying to implement pie chart from ios-charts library everything is working great, however I am missing legends from the graph -
Here is my code -
// This is the delegate method for creating data for chart
func offDaysDidLoaded(controller: DataModel,chartArray:[PFObject]) {
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM"
dataDict = [:]
for od in chartArray {
let date = od["Date"] as! NSDate
let month = formatter.stringFromDate(date)
if self.dateDict.indexForKey(month) != nil {
self.dateDict[month]! += 1.0
}else{
self.dateDict.updateValue(1.0, forKey: month)
}
}
let dataPointArray = Array(dateDict.keys)
let valuesArray = Array(dateDict.values)
pieChartView.data = nil
pieChartView.backgroundColor = UIColor.grayColor()
setChart(dataPointArray, values: valuesArray)
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
let pieChartDataSet = PieChartDataSet(yVals: dataEntries, label: "Months")
let pieChartData = PieChartData(xVals: dataPoints, dataSet: pieChartDataSet)
pieChartData.setDrawValues(false)
pieChartView.data = pieChartData
pieChartView.animate(xAxisDuration: NSTimeInterval(5))
var colors: [UIColor] = []
for _ in 0..<dataPoints.count {
let red = Double(arc4random_uniform(256))
let green = Double(arc4random_uniform(256))
let blue = Double(arc4random_uniform(256))
let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
colors.append(color)
}
pieChartDataSet.colors = colors
}
I have seen similar issue in here and build and run, pie chart used in the issue also doesn't show any legends below the chart. Any help or pointer would be really appreciated.
Thanks
Finally this issue is resolved it wasn't the bug. Please find the detailed solution here.
I just did try ChatsDemo with
legend.position = ChartLegendPositionBelowChartLeft;
works fine. So either your data problem, or you modified something. You don't show how you setup x values. Give more details or debug on your own. Should be easy

Resources