我有以下代码使用ChartsRealm在图表上显示折线。如何显示/隐藏图表上的个别线条?
let line1 = LineChartDataSet(values: lineChartEntry1, label: "CH4")
let line2 = LineChartDataSet(values: lineChartEntry2, label: "O2")
let line3 = LineChartDataSet(values: lineChartEntry3, label: "H2S")
line1.colors = [NSUIColor.blue]
line2.colors = [NSUIColor.green]
line3.colors = [NSUIColor.red]
let data = LineChartData()
data.addDataSet(line1)
data.addDataSet(line2)
data.addDataSet(line3)
chtChart.data = (data)
答案 0 :(得分:0)
因此,没有方法可以隐藏/显示图表库中的数据集。
但是我们可以在逻辑上做到这一点而无需刷新页面。
请检查以下代码是否相同:
创建LineChartView扩展程序:
extension LineChartView {
func setLineChartData(xValues: [String], labels: [String],dataSets:[Array<Double>],colors:[UIColor]) {
var dataSetsArray: [LineChartDataSet] = []
let dataSetCount = self.lineData?.dataSets.count
if dataSetCount != nil && dataSetCount! > 0 {
self.data = nil
}
for i in 0..<dataSets.count {
let yVals = dataSets[i]
var dataEntries: [ChartDataEntry] = []
for i in 0..<yVals.count {
let dataEntry = ChartDataEntry(x: Double(i), y: yVals[i])
dataEntries.append(dataEntry)
}
let chartDataSet = LineChartDataSet(values: dataEntries, label: labels[i])
chartDataSet.highlightEnabled = true
chartDataSet.drawHorizontalHighlightIndicatorEnabled = false
chartDataSet.highlightColor = .blue
chartDataSet.highlightLineWidth = 1
chartDataSet.lineWidth = 2.0
chartDataSet.mode = .horizontalBezier
chartDataSet.drawCircleHoleEnabled = true
chartDataSet.drawValuesEnabled = true
chartDataSet.axisDependency = .left
chartDataSet.circleHoleColor = colors[i]
chartDataSet.highlightColor = colors[i]
chartDataSet.colors = [colors[i]]
//Add Data Set Into Sets array
dataSetsArray.append(chartDataSet)
}
let chartData = LineChartData(dataSets: dataSetsArray)
self.data = chartData
self.animate(xAxisDuration: 1.0,easingOption: .easeInExpo)
}
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
}
}
通过将一种方法添加到LineChartView
扩展名中,然后根据您的要求或用户actin进行调用。
我是通过下面的细分更改方法调用的:
@IBAction func segmentValueChanged(_ sender: Any) {
switch self.lineSegment.selectedSegmentIndex {
case 0:
let colors = [UIColor.red,UIColor.green,UIColor.blue]
lineChartView.setLineChartData(xValues: months,
labels: ["Monthly Sales","Quarterly Sales","Yearly Sales"],
dataSets: [unitsSold,unitsSold1,unitsSold2],
colors: colors)
break
case 1:
lineChartView.setLineChartData(xValues: months,
labels: ["Monthly Sales"],
dataSets: [unitsSold],
colors: [UIColor.red])
break
case 2:
lineChartView.setLineChartData(xValues: months,
labels: ["Quarterly Sales"],
dataSets: [unitsSold1],
colors: [UIColor.green])
break
case 3:
lineChartView.setLineChartData(xValues: months,
labels: ["Yearly Sales"],
dataSets: [unitsSold2],
colors: [UIColor.blue])
break
default:
break
}
}
您可以根据需要在数据集中传递不同的数据。
检查以下屏幕以获取输出参考:
我的细分为全部 | 每月 | 季度 | 每年
希望这将帮助您达到要求!