我正在尝试创建一个饼图,该饼图在第一级显示国家(地区)数组,在第二级显示每个国家(地区)的城市。
我有一个JSON文件(如下),其中包含我修改过的数据,以便更接近我试图实现的目标,但它似乎不起作用(我可能离得太远了...)
[
{city: "Budapest", country: "Hungary"},
{city: "Shenzen", country: "China"},
{city: "Shenzen", country: "China"},
{city: "Shenzen", country: "China"},
{city: "Istanbul", country: "Turkey"},
{city: "Ho Chi Minh", country: "Vietnam"},
{city: "Shenzen", country: "China"},
{city: "Budapes", country: "Hungary"},
{city: "Budapest", country: "Hungary"},
{city: "Shenzen", country: "China"},
{city: "Shenzen", country: "China"},
{city: "Shenzen", country: "China"},
{city: "Istanbul", country: "Turkey"},
{city: "Budapest", country: "Hungary"},
{city: "Shenzen", country: "China"},
{city: "Shenzen", country: "China"},
{city: "Shenzen", country: "China"},
{city: "Istanbul", country: "Turkey"},
]
下面是我正在使用的修改后的数据:
[
{country: "Hungary", cities: ["Budapest", "Budapes", "Budapest", "Budapest"]},
{country: "Chine", cities: ["Shenzen", "Shenzen", "Shenzen"]},
{country: "Turkey", cities: ["Istanbul", "Istanbul", "Istanbul"]},
{country: "Vietnam", cities: ["Ho Chi Minh"]},
]
从本质上讲,我试图做一个饼图,显示4个国家在中间,每个切片,然后打破到每个国家的城市。任何帮助将是非常感谢。
用于修改数据的代码I:
let countries: any = [];
let intermediete: any = [
...new Set(data.map((col: any) => col.country)),
].reduce((a: any, v: any) => ({ ...a, [v]: [] }), {});
data.forEach((location: any) => {
intermediete[location.country].push(location.city);
});
for (let i = 0; i < Object.keys(intermediete).length; i++) {
countries.push({
country: Object.keys(intermediete)[i],
cities: Object.values(intermediete)[i],
});
}
data = countries;
console.log(data);
let cuntries_count: any = [];
let cities_count: any = [];
data
.map((col: any) => col.cities)
.forEach((element: any) => {
cuntries_count.push(element.length);
cities_count.push([...new Set(element)].length);
});
this.locations_pie_data = {
labels: Object.keys(intermediete),
datasets: [
{
type: 'doughnut',
data: cities_count,
backgroundColor: [...new Set(data.map(() => this.randomHEX()))],
},
{
type: 'doughnut',
data: cuntries_count,
backgroundColor: [...new Set(data.map(() => this.randomHEX()))],
},
],
options: {
rotation: 0,
circumference: 90,
plugins: {
legend: {
position: 'right',
},
},
},
};
});
所需的输出应类似于下图
(内圈〉国家,外圈〉每个国家的城市)
1条答案
按热度按时间v64noz0r1#
请看一下下面的可运行代码,看看它是如何完成的。
当涉及到
legend
时,您可能必须实现一个解决方案,如answer中所述。第一个