【发布时间】:2020-11-09 13:55:46
【问题描述】:
我需要创建一个堆叠的水平条形图,对于下面的代码,图表是水平的,但不是堆叠的。我为图表创建了一个单独的组件,并在另一个组件中使用它,我浏览了几篇堆积如山的溢出文章,但没有帮助。我无法找出问题所在。非常感谢任何帮助。
horizontal-chart.component.ts
export class HorizontalBarchartComponent implements OnInit {
dataCtx: any;
bar_chart: any;
@ViewChild('horizontalbarChart') horizontalbarChartRef: ElementRef;
@Input() data = [];
@Input() yLabel: any;
@Input() xLabel: any;
@Input() nameObj?: any;
@Input() stacked:boolean;
@Input() hoverData:Array<any>;
colors: Array<string> = ["rgba(98, 228, 98, 1)", "rgba(248, 227, 117, 1)", "rgba(250, 99,131, 1)"]
constructor() { }
ngAfterViewInit() {
this.renderChart();
}
ngOnChanges() {
if (this.horizontalbarChartRef){
this.renderChart();
}
}
renderChart() {
this.dataCtx = this.horizontalbarChartRef.nativeElement.getContext('2d');
this.bar_chart = new Chart(this.dataCtx, {
type: 'horizontalBar',
data: {
labels: this.nameObj.map(obj => obj.name),
datasets:this.setData()
},
options: {
legend: {
display: true,
position: 'bottom',
labels: {
padding: 20,
fontStyle: 'bold',
fontSize: 12,
}
},
scales: {
xAxes: [{
stacked: true,
position:'top',
display: true,
scaleLabel: {
display: true,
fontStyle: 'bold',
labelString: this.yLabel
},
ticks: {
autoSkip: false,
beginAtZero: true,
max:10
},
gridLines: {
display:false,
}
}],
yAxes: [{
stacked: true,
categoryPercentage: 1,
maxBarThickness: 50,
display: true,
scaleLabel: {
display: true,
fontStyle: 'bold',
labelString: this.xLabel
},
ticks: {
min: 0,
},
gridLines: {
display:false
}
}]
},
responsive: true,
}
});
}
setData(){
let fixed_options ={
borderColor: 'transparent',
borderWidth: 2,
pointBorderColor: 'transparent',
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: "#fff",
pointHighlightFill: "#fff",
pointRadius: 3,
pointHitRadius: 20,
pointBorderWidth: 1,
}
if(this.stacked){
let subData = [];
this.data.filter((d,index) => { subData.push({"data":d, "backgroundColor": this.colors[index],"label": this.hoverData[index], fixed_options }) });
return subData;
}
else{
return [{"data": this.data,"backgroundColor":'rgba(98, 228, 98, 1)',"label":`Upload/Sketch's Per Factor Scores`}]
}
} }
另一个.component.html
<horizontal-barchart class="col-md-10" [data]="horizontalBar.data" yLabel="Percentage"
[xLabel]="'student names'" [nameObj]="quizOrTestAnalysis" [stacked]="true"
[hoverData]="['Proficient Answers', 'Elimination Answers', 'Random Answers']">
</horizontal-barchart>
另一个.component.ts
horizontalBar = {
data:[[10],[20],[30]],
}
【问题讨论】:
标签: javascript angular charts