使用Chart.js的双层圆环图

eeq64g8w  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(308)

我正在尝试创建一个饼图,该饼图在第一级显示国家(地区)数组,在第二级显示每个国家(地区)的城市。
我有一个JSON文件(如下),其中包含我修改过的数据,以便更接近我试图实现的目标,但它似乎不起作用(我可能离得太远了...)

  1. [
  2. {city: "Budapest", country: "Hungary"},
  3. {city: "Shenzen", country: "China"},
  4. {city: "Shenzen", country: "China"},
  5. {city: "Shenzen", country: "China"},
  6. {city: "Istanbul", country: "Turkey"},
  7. {city: "Ho Chi Minh", country: "Vietnam"},
  8. {city: "Shenzen", country: "China"},
  9. {city: "Budapes", country: "Hungary"},
  10. {city: "Budapest", country: "Hungary"},
  11. {city: "Shenzen", country: "China"},
  12. {city: "Shenzen", country: "China"},
  13. {city: "Shenzen", country: "China"},
  14. {city: "Istanbul", country: "Turkey"},
  15. {city: "Budapest", country: "Hungary"},
  16. {city: "Shenzen", country: "China"},
  17. {city: "Shenzen", country: "China"},
  18. {city: "Shenzen", country: "China"},
  19. {city: "Istanbul", country: "Turkey"},
  20. ]

下面是我正在使用的修改后的数据:

  1. [
  2. {country: "Hungary", cities: ["Budapest", "Budapes", "Budapest", "Budapest"]},
  3. {country: "Chine", cities: ["Shenzen", "Shenzen", "Shenzen"]},
  4. {country: "Turkey", cities: ["Istanbul", "Istanbul", "Istanbul"]},
  5. {country: "Vietnam", cities: ["Ho Chi Minh"]},
  6. ]

从本质上讲,我试图做一个饼图,显示4个国家在中间,每个切片,然后打破到每个国家的城市。任何帮助将是非常感谢。
用于修改数据的代码I:

  1. let countries: any = [];
  2. let intermediete: any = [
  3. ...new Set(data.map((col: any) => col.country)),
  4. ].reduce((a: any, v: any) => ({ ...a, [v]: [] }), {});
  5. data.forEach((location: any) => {
  6. intermediete[location.country].push(location.city);
  7. });
  8. for (let i = 0; i < Object.keys(intermediete).length; i++) {
  9. countries.push({
  10. country: Object.keys(intermediete)[i],
  11. cities: Object.values(intermediete)[i],
  12. });
  13. }
  14. data = countries;
  15. console.log(data);
  16. let cuntries_count: any = [];
  17. let cities_count: any = [];
  18. data
  19. .map((col: any) => col.cities)
  20. .forEach((element: any) => {
  21. cuntries_count.push(element.length);
  22. cities_count.push([...new Set(element)].length);
  23. });
  24. this.locations_pie_data = {
  25. labels: Object.keys(intermediete),
  26. datasets: [
  27. {
  28. type: 'doughnut',
  29. data: cities_count,
  30. backgroundColor: [...new Set(data.map(() => this.randomHEX()))],
  31. },
  32. {
  33. type: 'doughnut',
  34. data: cuntries_count,
  35. backgroundColor: [...new Set(data.map(() => this.randomHEX()))],
  36. },
  37. ],
  38. options: {
  39. rotation: 0,
  40. circumference: 90,
  41. plugins: {
  42. legend: {
  43. position: 'right',
  44. },
  45. },
  46. },
  47. };
  48. });

所需的输出应类似于下图
(内圈〉国家,外圈〉每个国家的城市)

v64noz0r

v64noz0r1#

请看一下下面的可运行代码,看看它是如何完成的。
当涉及到legend时,您可能必须实现一个解决方案,如answer中所述。
第一个

相关问题