I am using Charts v3.2.2 framework by danielgindi for iOS and macOS to draw a RadarChartView. There is a github repository that provides an example xcode project including Playgrounds. One is for RadarChartView.
Following the example I can set RadarChartData with two different RadarChartDataSets
var chartView = RadarChartView(frame: rect)
let data = RadarChartData(dataSets: [set1, set2])
chartView.data = data
It shows a chart like this:
The green labels set to x-axis are numbers from 0.0 to 4.0, but they should be string labels.
I cannot figure out how to set these labels that should be drawn around the RadarChart at the end of each web line. I guess it should be something like this:
data.setLabels("London", "Paris", "Berlin", "New York", "Tokio")
But this isn't working although it is a feature of class RadarChartData to set the desired labels.
Can somebody help me with that issue?
EDIT: complete code example
import Cocoa
import Charts
import PlaygroundSupport
let r = CGRect(x: 0, y: 0, width: 400, height: 400)
var chartView = RadarChartView(frame: r)
// General settings
chartView.webColor = NSUIColor.lightGray
chartView.innerWebColor = NSUIColor.lightGray
chartView.webAlpha = 1.0
// xAxis settings
let xAxis = chartView.xAxis
xAxis.xOffset = 0.0
xAxis.yOffset = 0.0
xAxis.labelTextColor = NSUIColor.green
xAxis.drawLabelsEnabled = true
// yAxis settings
let yAxis = chartView.yAxis
yAxis.labelCount = 5
yAxis.axisMinimum = 0.0
yAxis.axisMaximum = 80.0
yAxis.drawLabelsEnabled = true
// Legend settings
let legend = chartView.legend
// ... (irrelevant)
// Description
chartView.chartDescription?.enabled = true
chartView.chartDescription?.text = "Radar demo"
chartView.chartDescription?.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
// RadarChartDataEntry
let mult = 80.0
let min = 20.0
let cnt = 5
var entries1 = [RadarChartDataEntry]()
var entries2 = [RadarChartDataEntry]()
for i in 1...cnt
{
let values1 = (Double(arc4random_uniform(UInt32(mult))) + min)
entries1.append(RadarChartDataEntry(value: values1, data: "a" as AnyObject))
let values2 = (Double(arc4random_uniform(UInt32(mult))) + min)
entries2.append(RadarChartDataEntry(value: values2, data: "b" as AnyObject))
}
// RadarChartDataSet
let set1 = RadarChartDataSet(entries: entries1, label: "Last Week")
set1.drawFilledEnabled = true
set1.fillAlpha = 0.7
set1.lineWidth = 2.0
set1.drawHighlightCircleEnabled = true
set1.setDrawHighlightIndicators(false)
let set2 = RadarChartDataSet(entries: entries2, label: "This Week")
set2.drawFilledEnabled = true
set2.fillAlpha = 0.7
set2.lineWidth = 2.0
set2.drawHighlightCircleEnabled = true
set2.setDrawHighlightIndicators(false)
// RadarChartData
let data = RadarChartData(dataSets: [set1, set2])
data.setLabels("London", "Paris", "Berlin", "New York", "Tokio")
data.setDrawValues ( true )
data.setValueTextColor( NSUIColor.white )
chartView.data = data
chartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .easeInBounce)
// show chartView
PlaygroundPage.current.liveView = chartView
You need to override IAxisValueFormatter func stringForValue(_ value: Double, axis: AxisBase?) -> String {} function.
Like below:
Step1: Customize your xAxis with custom formatter.
let xValues = ["X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8", "X9", "X10"]
let chartFormatter = RadarChartFormatter(labels: xValues)
let xAxis = XAxis()
xAxis.valueFormatter = chartFormatter
self.xAxis.valueFormatter = xAxis.valueFormatter
Step2: Implement Custom formatter with below method.
private class RadarChartFormatter: NSObject, IAxisValueFormatter {
var labels: [String] = []
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
if Int(value) < labels.count {
return labels[Int(value)]
}else{
return String("")
}
}
init(labels: [String]) {
super.init()
self.labels = labels
}
}
You will get below output in your RadarCharView:
Hope this will help you to get your custom labels on Radar chart!
Related
I wanna create a chart with 7 days only on the x-axis
I wanna plot readings according to the day and hours they have been saved at but only show days' names.
time format: Thursday-7:23 pm which is something like "dd - HH: MM a"
import UIKit
import Charts
import TinyConstraints
class ViewController: UIViewController,ChartViewDelegate{
lazy var lineChartView: LineChartView = {
let chartView = LineChartView()
//X-axis
chartView.xAxis.centerAxisLabelsEnabled = false
chartView.xAxis.setLabelCount(7, force: true)//sets x axis to have 7 values
let xAxis = lineChartView.xAxis
chartView.xAxis.axisLineWidth = 1.5
chartView.xAxis.drawGridLinesEnabled = false//hides x-axis grids
//chartView.xAxis.valueFormatter??
chartView.animate(xAxisDuration: 2.5)
return chartView
}()
func setChartData() {
//create a set for line 1
let color1 = NSUIColor(red: CGFloat(140.0/255.0), green: CGFloat(170.0/255.0), blue: CGFloat(177.0/255.0), alpha: 1)
let set1 = LineChartDataSet(entries: yValues, label: "hello")
set1.mode = .cubicBezier //makes curves smoother
set1.setCircleColor(color1)
set1.circleRadius = 6
set1.circleHoleRadius = 3
set1.lineWidth = 3
set1.setColor(color1)
//create a line chart data
let data1 = LineChartData(dataSet: set1)
data1.setDrawValues(false)//hides values on markers
//add data to lineChartView
lineChartView.data = data1
}
let yValues: [ChartDataEntry] = [
ChartDataEntry(x: 0.0, y: 10.0),
ChartDataEntry(x: 1.0, y: 5.0),
ChartDataEntry(x: 2.0, y: 7.0),
]
}
I'm using the Charts library and am trying to replicate this design:
I'm sort of getting there, but the chart is rendering itself way too small:
I'm expecting the chart to fill the entire width of the screen, and use all the vertical space. To be clear: the RadarChartView is the width of the entire black area, and the entire vertical space right up to the legend (which is not part of the chart view itself).
Any ideas?
This is the table cell code that shows the chart:
import Charts
import UIKit
final class ReportSpiderChart: UITableViewCell {
private let labels = ["ARTISTS", "TRACKS", "ALBUMS"]
#IBOutlet private var chartView: RadarChartView!
override func awakeFromNib() {
super.awakeFromNib()
chartView.webLineWidth = 1
chartView.innerWebLineWidth = 1
chartView.webColor = .init(hex: "28282A")
chartView.innerWebColor = .init(hex: "28282A")
chartView.legend.enabled = false
let xAxis = chartView.xAxis
xAxis.labelFont = .systemFont(ofSize: 11, weight: .semibold)
xAxis.xOffset = 0
xAxis.yOffset = 0
xAxis.labelTextColor = .init(hex: "919198")
xAxis.valueFormatter = self
let yAxis = chartView.yAxis
yAxis.labelCount = 3
yAxis.labelFont = .systemFont(ofSize: 11, weight: .semibold)
yAxis.labelTextColor = .init(hex: "919198")
yAxis.axisMinimum = 0
yAxis.drawLabelsEnabled = false
}
func configure(data: ReportData) {
let entries: [RadarChartDataEntry] = [
.init(value: Double(data.artists)),
.init(value: Double(data.tracks)),
.init(value: Double(data.albums)),
]
chartView.yAxis.axisMaximum = Double(max(max(data.artists, data.tracks), data.albums))
let dataSet = RadarChartDataSet(entries: entries)
dataSet.fillColor = UIColor(hex: "FA4B4B").withAlphaComponent(0.75)
dataSet.fillAlpha = 0.75
dataSet.drawFilledEnabled = true
dataSet.lineWidth = 0
dataSet.drawHighlightCircleEnabled = false
dataSet.setDrawHighlightIndicators(false)
let data = RadarChartData(dataSets: [dataSet])
data.setDrawValues(false)
chartView.data = data
}
}
extension ReportSpiderChart: IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return labels[Int(value) % labels.count]
}
}
It seems that their is a spaceTop and spaceBottom property on axis, did you try to set them to 0 on both axis ?
https://github.com/danielgindi/Charts/blob/1bbec78109c7842d130d53ff8811bb6dbe865ba4/Source/Charts/Components/YAxis.swift#L72
I am trying to simple line chart. Chart is coming fine and I want to add values/names for every point of x and y axis.
See the following image, this is is comming , but I want to add/show values in x and y axis.
For example: Check in my example code, I mentioned months and unitSold values.
in X axis I wants to show months names and Y axis and I wants to show some unit sold values.
How can I do or show values in x and y axis?
import UIKit
import Charts
class ViewController: UIViewController {
var dataEntries: [ChartDataEntry] = []
// var chartDataBeanArray = [ChartDataBean]()
let months = ["Jan" , "Feb", "Mar", "Apr", "May", "June", "July", "August", "Sept", "Oct", "Nov", "Dec"]
let unitsSold = [24.0,43.0,56.0,23.0,56.0,68.0,48.0,120.0,41.0,34.0,55.9,12.0,34.0]
#IBOutlet weak var chartViewOutlet: LineChartView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setChart(months, values: unitsSold)
}
func setChart(_ dataPoints: [String], values: [Double]) {
print(values)
print(dataPoints)
chartViewOutlet.noDataText = "No data available!"
for i in 0..<values.count {
print("chart point : \(values[i])")
let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
}
let line1 = LineChartDataSet(entries: dataEntries, label: "Units Consumed")
line1.colors = [NSUIColor.blue]
line1.mode = .cubicBezier
line1.cubicIntensity = 0.2
let gradient = getGradientFilling()
line1.fill = Fill.fillWithLinearGradient(gradient, angle: 90.0)
line1.drawFilledEnabled = true
let data = LineChartData()
data.addDataSet(line1)
chartViewOutlet.data = data
chartViewOutlet.setScaleEnabled(false)
chartViewOutlet.animate(xAxisDuration: 1.5)
chartViewOutlet.drawGridBackgroundEnabled = false
chartViewOutlet.xAxis.drawAxisLineEnabled = false
chartViewOutlet.xAxis.drawGridLinesEnabled = false
chartViewOutlet.leftAxis.drawAxisLineEnabled = false
chartViewOutlet.leftAxis.drawGridLinesEnabled = false
chartViewOutlet.rightAxis.drawAxisLineEnabled = false
chartViewOutlet.rightAxis.drawGridLinesEnabled = false
chartViewOutlet.legend.enabled = false
chartViewOutlet.xAxis.enabled = false
chartViewOutlet.leftAxis.enabled = false
chartViewOutlet.rightAxis.enabled = false
chartViewOutlet.xAxis.drawLabelsEnabled = false
}
/// Creating gradient for filling space under the line chart
private func getGradientFilling() -> CGGradient {
// Setting fill gradient color
let coloTop = UIColor(red: 141/255, green: 133/255, blue: 220/255, alpha: 1).cgColor
let colorBottom = UIColor(red: 230/255, green: 155/255, blue: 210/255, alpha: 1).cgColor
// Colors of the gradient
let gradientColors = [coloTop, colorBottom] as CFArray
// Positioning of the gradient
let colorLocations: [CGFloat] = [0.7, 0.0]
// Gradient Object
return CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors, locations: colorLocations)!
}
}
EDIT : After adding following code suggested by #marc
chartViewOutlet.xAxis.enabled = true
chartViewOutlet.leftAxis.enabled = true
this is now showing chart.
Now I wants to show months values in bottom (x axis)...how to show it?
You can find source code here if you want to check it: https://drive.google.com/file/d/1vkPqktZ3mX3q9f75-bihVYeublwc2dXE/view?usp=sharing
Add following code in your project.
func setChart(dataPoints: [String], values: [Double]) {
for i in 0 ..< dataPoints.count {
dataEntries.append(ChartDataEntry(x: Double(i), y: values[i]))
}
let lineChartDataSet = LineChartDataSet(entries: dataEntries, label: "Units Consumed")
lineChartDataSet.axisDependency = .left
lineChartDataSet.setColor(UIColor.black)
lineChartDataSet.setCircleColor(UIColor.black) // our circle will be dark red
lineChartDataSet.lineWidth = 1.0
lineChartDataSet.circleRadius = 3.0 // the radius of the node circle
lineChartDataSet.fillAlpha = 1
lineChartDataSet.fillColor = UIColor.black
lineChartDataSet.highlightColor = UIColor.white
lineChartDataSet.drawCircleHoleEnabled = true
var dataSets = [LineChartDataSet]()
dataSets.append(lineChartDataSet)
let lineChartData = LineChartData(dataSets: dataSets)
chartViewOutlet.data = lineChartData
chartViewOutlet.rightAxis.enabled = false
chartViewOutlet.xAxis.drawGridLinesEnabled = false
chartViewOutlet.xAxis.labelPosition = .bottom
chartViewOutlet.xAxis.valueFormatter = IndexAxisValueFormatter(values: dataPoints)
chartViewOutlet.legend.enabled = true
}
Output:
This works 100%. Try it.
I'm making a chart by using chart iOS framework. but the value will overlay when the slice is tiny. How can I hide it? This question is similar to this GitHub link, But I don't understand how it works. Do I just need to add the code in my View Controller or drag the PieChartRenderer.swift file to my project?
Can someone explain to me how to use the pull request or some open public function...
Sorry I'm new in iOS framework.
This is my code.
#IBOutlet weak var myChart: PieChartView!
var valueColors = [UIColor]()
var dataEntries = [PieChartDataEntry]()
var record = [Record]()
var category = [String]()
var categoryTotal : [Double] = []
var categoryArray : [String] = []
func setDataCount() {
valueAndColor()
let set = PieChartDataSet(values: dataEntries, label: nil)
set.colors = valueColors
set.valueLinePart1OffsetPercentage = 0.8
set.valueLinePart1Length = 0.2
set.valueLinePart2Length = 0.4
set.xValuePosition = .outsideSlice
set.yValuePosition = .outsideSlice
set.selectionShift = 0.0
let data = PieChartData(dataSet: set)
let Formatter:ChartFormatter = ChartFormatter()
data.setValueFormatter(Formatter)
data.setValueFont(.systemFont(ofSize: 11, weight: .light))
data.setValueTextColor(.black)
myChart.data = data
myChart.highlightValues(nil)
}
func setup(pieChartView chartView: PieChartView) {
chartView.usePercentValuesEnabled = true
chartView.drawSlicesUnderHoleEnabled = true
chartView.holeRadiusPercent = 0.58
chartView.chartDescription?.enabled = false
chartView.drawCenterTextEnabled = true
chartView.centerAttributedText = attributedString;
chartView.drawHoleEnabled = true
chartView.rotationAngle = 0
chartView.rotationEnabled = true
chartView.highlightPerTapEnabled = true
}
func valueAndColor(){
for i in 0..<categoryArray.count{
let dataEntry = PieChartDataEntry(value: categoryTotal[i], label: categoryArray[i % categoryArray.count])
dataEntries.append(dataEntry)
if categoryArray[i] == "εε" {
valueColors.append(UIColor.yellow)
}else if categoryArray[i] == "δΊ€ι"{
valueColors.append(UIColor.red)
}...
}
Create a custom formatter, I set the minNumber as 10.0 and the empty string is returned when a value is less than the minNumber, otherwise the value is returned.
public class ChartFormatter: NSObject, IValueFormatter{
public func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
let total = UserDefaults.standard.double(forKey: "totalValue")
var valueToUse = value/total * 100
valueToUse = Double(round(10*valueToUse)/10)
print("valueToUse: \(valueToUse)")
let minNumber = 10.0
if(valueToUse<minNumber) {
return ""
}
else {
return String(valueToUse) + "%"
}
}
}
Then make sure you set the totalValue variable, store it in UserDefaults (to make it possible to access it in the formatter) and set the formatter for your graph
var totalValue = 0.0
let units = [10.0, 4.0, 6.0, 3.0, 12.0, 16.0]
for a in units {
totalValue += a
}
UserDefaults.standard.set(totalValue, forKey: "totalValue")
let formatter:ChartFormatter = ChartFormatter()
data.setValueFormatter(formatter)
Result:
Newer versions of the Charts library have added this feature and made it a simple property to set on the instance of the PieChartView:
pieChart.sliceTextDrawingThreshold = 20
The sliceTextDrawingThreshold property sets the minimum angle that is required for a label to be drawn.
I am trying to setup a line chart with one fill colour but for some reason, the fill colour is faded.
Example
Both the random view I have added to middle of screen and the fill colour of the line chart are set to be red, but for some reason the fill colour of the chart is faded.
Can see code here
#IBOutlet var liveChart : LineChartView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Chart Tests"
configureChart(chart: liveChart)
var xAxis = [String]()
var yAxis = [Double]()
for _ in 0..<10
{
xAxis.append("")
let yVal = Double(randomBetweenNumbers(firstNum: 1.0, secondNum: 100.0))
yAxis.append(yVal)
}
setData(xAxisArray: xAxis, yAxisArray: yAxis, chart: liveChart)
let testView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
testView.center = view.center
testView.backgroundColor = UIColor.red
view.addSubview(testView)
}
func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{
return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
}
func configureChart(chart : LineChartView)
{
chart.chartDescription?.text = ""
chart.noDataText = "Loading Data"
chart.backgroundColor = UIColor.clear
chart.drawGridBackgroundEnabled = false
chart.dragEnabled = true
chart.rightAxis.enabled = false
chart.leftAxis.enabled = true
chart.doubleTapToZoomEnabled = false
chart.legend.enabled = false
chart.pinchZoomEnabled = true
chart.highlightPerTapEnabled = false
chart.highlightPerDragEnabled = false
chart.xAxis.enabled = false
chart.leftAxis.drawAxisLineEnabled = false
chart.leftAxis.drawGridLinesEnabled = false
chart.leftAxis.labelCount = 5
chart.leftAxis.forceLabelsEnabled = true
}
func setData(xAxisArray : [String], yAxisArray : [Double], chart : LineChartView)
{
var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
if(xAxisArray.count > 0)
{
for i in 0 ..< xAxisArray.count
{
let chartEntry = ChartDataEntry(x: Double(i), y: yAxisArray[i], data: nil)
yVals1.append(chartEntry)
}
}
let set1: LineChartDataSet = LineChartDataSet(values: yVals1, label: "")
set1.fillColor = UIColor.red
set1.drawFilledEnabled = true
set1.drawCirclesEnabled = false
let data = LineChartData()
data.addDataSet(set1)
liveChart.data = data
}
Is there a way to fix this? Or is this just the way the fill colour of the chart works?
Edit:
I am using
https://github.com/danielgindi/Charts
I assume you use this library: https://github.com/kevinbrewster/SwiftCharts
So the LineChartView automatically set alpha for the fill color: https://github.com/kevinbrewster/SwiftCharts/blob/master/SwiftCharts/LineChart.swift#L758
try to set fillAlpha property of the data set