I want to plot the data stored in coredata as a chart. (using SwiftUI)
The entity structure of the project is as follows. entity name: Item attribute : name(String), success(Int), date(Date)
Among the above attributes, I want to draw the trend of the success attribute as a bar chart.
I did find a suitable package for drawing charts. It is 'Charts' by appear.
To draw a chart, you need to put success data in the data array, which is difficult.
Either way it doesn't matter. Please suggest a specific way to draw a chart.
For reference, I am attaching the code I used.
import SwiftUI
import SwiftUICharts
import CoreData
struct ChartView: View{
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest var items: FetchedResults<Item>
var demoData: [Double] = []
@State var thinkData = []
init() {
let request: NSFetchRequest<Item> = Item.fetchRequest()
request.sortDescriptors = [
NSSortDescriptor(keyPath: \Item.date, ascending: true)
]
request.fetchLimit = 7
_items = FetchRequest(fetchRequest: request)
for i in items{
demoData.append(Double(i.success))
}
}
var body: some View{
HStack{
Spacer()
BarChart()
.data(aData)
.chartStyle(ChartStyle(backgroundColor: .white,
foregroundColor: ColorGradient(.blue, .purple)))
Spacer()
}
}
}