iOS-Chart チャートデータ非表示、Descriptionの端末種類、オリエンテーションでの適正化

iOS-Chartは人気グラフィックライブラリーなのですが、マニュアルがないのがネック。試行錯誤したなかの情報も含めて共有します。

CocoapodsのPodfileのメタ情報は


platform :ios, ‘OSバージョン’
use_frameworks! target ‘アプリ名’ do
pod ‘Charts’
end

そしてターミナルから

$ pod install

バーチャート作成のコードサンプルは

let y2Vals: [Double] = [ 900, 800, 1000, 500, 800, 900, 300, 400, 100, 1200, 500, 100]
xduration= [“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”]

var entries2 = [BarChartDataEntry]()

for (i, v) in y2Vals.enumerated() {
let entry = BarChartDataEntry()
entry.x = Double(i)
entry.y = v
entry.data = xduration as AnyObject //x軸に文字列を指定する場合
entries2.append(entry)
}

let set2 = BarChartDataSet(values: entries2, label: “2016”)
set2.setColor(UIColor.flatSkyBlue)

// チャートのスタイルの設定

BarChartView.xAxis.labelPosition = .bottom
BarChartView.drawValueAboveBarEnabled = true
BarChartView.xAxis.drawGridLinesEnabled = false
BarChartView.leftAxis.drawGridLinesEnabled = true
BarChartView.rightAxis.drawGridLinesEnabled = false
BarChartView.leftAxis.drawLabelsEnabled = true
BarChartView.rightAxis.drawLabelsEnabled = false

// チャートの間隔の調整

let data = BarChartData(dataSets: dataSets) let groupSpace = 0.25
let barSpace = 0.0
let barWidth = 0.3
let groupCount = self.xdurationtype.count
let startYear = 0

data.barWidth = barWidth;
BarChartView.xAxis.axisMinimum = Double(startYear)
let gg = data.groupWidth(groupSpace: groupSpace, barSpace: barSpace)
BarChartView.xAxis.axisMaximum = Double(startYear) + gg * Double(groupCount)
data.groupBars(fromX: Double(startYear), groupSpace: groupSpace, barSpace: barSpace)
BarChartView.notifyDataSetChanged()

// グラフ上のデータを非表示

let chartData = BarChartData()
chartData.addDataSet(set)
chartData.setDrawValues(false)

// オリエンテーション、デバイスタイプによりDescriptionの位置を変更

switch UIDevice.current.userInterfaceIdiom { // Detect Device Type and Orientation for Description location

case .phone:
if UIDevice.current.orientation.isLandscape {
self.MyChartView.chartDescription?.position = CGPoint(x: 適切な数値を設定, y: 0)
} else {
self.BarChartView.chartDescription?.position = CGPoint(x: 適切な数値を設定, y: 0)
}
case .pad:
if UIDevice.current.orientation.isLandscape {
self.MyChartView.chartDescription?.position = CGPoint(x: 適切な数値を設定, y: 0)
} else {
self.MyChartView.chartDescription?.position = CGPoint(x: 適切な数値を設定, y: 0)
}
default:
if UIDevice.current.orientation.isLandscape {
self.MyChartView.chartDescription?.position = CGPoint(x: 適切な数値を設定, y: 0)
} else {
self.MyChartView.chartDescription?.position = CGPoint(x: 適切な数値を設定, y: 0)
}
}

詳しくは https://github.com/danielgindi/Charts