Using custom theme to apply patterns to pie chart slices
This demo shows how we can build a custom theme that applies distinctive patterns to each slice of a pie chart.
/** * --------------------------------------- * This demo was created using amCharts 5. * * For more information visit: * https://www.amcharts.com/ * * Documentation is available at: * https://www.amcharts.com/docs/v5/ * --------------------------------------- */
// Create root and chartvar root = am5.Root.new("chartdiv");
class MyTheme extends am5.Theme { setupDefaultRules() { var theme = this;
this.patterns = [ am5.LinePattern.new(this._root, { color: am5.color(0xffffff), rotation: 45 }),
am5.RectanglePattern.new(this._root, { color: am5.color(0xffffff) }),
am5.CirclePattern.new(this._root, { color: am5.color(0xffffff) }) ];
this.currentPattern = 0;
this.rule("Slice").setAll({ fillOpacity: 0.2 });
this.rule("Slice").setup = function (target) { target.set("fillPattern", theme.patterns[theme.currentPattern]); theme.currentPattern++; if (theme.currentPattern == theme.patterns.length) { theme.currentPattern = 0; } }; }}
root.setThemes([am5themes_Animated.new(root), MyTheme.new(root)]);
var chart = root.container.children.push( am5percent.PieChart.new(root, { layout: root.verticalLayout }));
// Define datavar data = [ { country: "France", sales: 100000 }, { country: "Spain", sales: 160000 }, { country: "United Kingdom", sales: 80000 }];
// Create seriesvar series = chart.series.push( am5percent.PieSeries.new(root, { name: "Series", valueField: "sales", categoryField: "country" }));
series.data.setAll(data);
// Add legendvar legend = chart.children.push( am5.Legend.new(root, { centerX: am5.percent(50), x: am5.percent(50), layout: root.horizontalLayout }));
legend.data.setAll(series.dataItems);<div id="chartdiv"></div>body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";}
#chartdiv { width: 100%; height: 95vh;}{ "type": "PieChart", "settings": { "layout": { "type": "VerticalLayout" } }, "properties": { "series": [ "#series-0" ] }, "children": [ { "type": "Legend", "settings": { "centerX": { "type": "Percent", "value": 50 }, "x": { "type": "Percent", "value": 50 }, "layout": { "type": "HorizontalLayout" } }, "properties": { "data": "#series-0.dataItems" } } ], "refs": [ { "data-0": [ { "country": "France", "sales": 100000 }, { "country": "Spain", "sales": 160000 }, { "country": "United Kingdom", "sales": 80000 } ] }, { "series-0": { "type": "PieSeries", "settings": { "name": "Series", "valueField": "sales", "categoryField": "country" }, "properties": { "data": "#data-0" } } } ]}using-custom-theme-to-apply-patterns-to-pie-chart-slices