我正在玩一个骨干木偶应用程序试图动态填充高价图数据,但我遇到了一些麻烦。
我创建了一个基本的调查应用程序,我想创建一个显示每个问题结果的图表。但是,我不知道调查可能有多少问题,或者每个问题可能有多少答案。
所以我所做的就是填充一个类似于answerArray[answerId] = numberOfTimesSelected
的数组:
questions: (survey) =>
questions = survey.get('questions')
questions.each (question) =>
length = question.get('answers').length
answers = question.get('answers')
answerArray = []
if length < 7
question.get('answers').each (answer) ->
answerArray[answer.id] = 0
survey.get('responses').each (response) =>
date = Math.floor(new Date(response.get('created_date')) / 86400000)
if date > (@minDate - 1) && date < (@maxDate + 1)
if response.get('completed')
choices = response.get('choices')
choices.each (choice) ->
if choice.get('question_id') == question.get('id')
answerArray[choice.get('answer_id')] = answerArray[choice.get('answer_id')] + 1
现在填充一个高级图表:
$('#' + question.get('id')).highcharts({
chart: {
marginRight: 50,
marginTop: 0,
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: '',
style: {
fontSize: 10
}
},
tooltip: {
pointFormat: '<b>{point.percentage:.1f}%</b>'
},
credits: {
enabled: false
},
exporting: {
enabled: true
},
plotOptions: {
pie: {
size: 300,
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: question.get('title'),
states: {
hover: {
brightness: 0
}
},
data: [
{
name: "14-17",
y: 22,
color: "#E8DF66"
},
{
name: "18-24",
y: 42,
color: "#8C8C8B"
},
{
name: "25-34",
y: 11,
color: "#687D68"
},
{
name: "35-44",
y: 55,
color: "#217C7E"
},
{
name: "45-54",
y: 231,
color: "#BEE7E8"
},
{
name: "55+",
y: 224,
color: "#634357"
}
]
}]
})
因此,我可以使用该静态数据填充每个问题的图表。但我需要一些方法来动态更改数据。像
这样的东西data: [ question.get('answers').each (answer) ->
{
name: answer.get('title'),
y: answerArray[answer.get('id')],
color: "#E8DF66"
}
]
但这实际上并不奏效。任何想法我怎么能做那样的事情?
答案 0 :(得分:1)
所以我最终动态为每个对象创建一个对象,然后创建一个对象的数组并使用该数组作为数据。
创建数组/对象:
graphData = []
question.get('answers').each (answer) ->
graphPiece = {}
graphPiece["name"] = answer.get('title')
graphPiece["y"] = answerArray[answer.get('id')]
graphPiece["color"] = "#E8DF66"
graphData.push(graphPiece)
使用highcharts图表中的数据:
series: [{
type: 'pie',
name: question.get('title'),
states: {
hover: {
brightness: 0
}
},
data: graphData
}]