Custom Slice or Sector Colors in Pie Chart

Contents
[ ]

To set a custom color for a pie chart’s individual slices or sectors:

  1. Access the Series object’s ChartPoint.
  2. Assign the color of your choice using the ChartPoint.area.foreground_color property.

This article also explains how to:

  • A chart’s category data.
  • A chart title linked to a cell.
  • The chart title font settings.
  • The position of the legend.
from aspose.cells import SaveFormat, Workbook
from aspose.cells.charts import ChartType, LegendPositionType
from aspose.pydrawing import Color
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# The path to the documents directory.
dataDir = RunExamples.GetDataDir(".")
# Create a workbook object from the template file
workbook = Workbook()
# Access the first worksheet.
worksheet = workbook.worksheets[0]
# Put the sample values used in a pie chart
worksheet.cells.get("C3").put_value("India")
worksheet.cells.get("C4").put_value("China")
worksheet.cells.get("C5").put_value("United States")
worksheet.cells.get("C6").put_value("Russia")
worksheet.cells.get("C7").put_value("United Kingdom")
worksheet.cells.get("C8").put_value("Others")
# Put the sample values used in a pie chart
worksheet.cells.get("D2").put_value("% of world population")
worksheet.cells.get("D3").put_value(25)
worksheet.cells.get("D4").put_value(30)
worksheet.cells.get("D5").put_value(10)
worksheet.cells.get("D6").put_value(13)
worksheet.cells.get("D7").put_value(9)
worksheet.cells.get("D8").put_value(13)
# Create a pie chart with desired length and width
pieIdx = worksheet.charts.add(ChartType.PIE, 1, 6, 15, 14)
# Access the pie chart
pie = worksheet.charts[pieIdx]
# Set the pie chart series
pie.n_series.add("D3:D8", True)
# Set the category data
pie.n_series.category_data = "=Sheet1!$C$3:$C$8"
# Set the chart title that is linked to cell D2
pie.title.linked_source = "D2"
# Set the legend position at the bottom.
pie.legend.position = LegendPositionType.BOTTOM
# Set the chart title's font name and color
pie.title.font.name = "Calibri"
pie.title.font.size = 18
# Access the chart series
srs = pie.n_series[0]
# Color the indvidual points with custom colors
srs.points[0].area.foreground_color = Color.from_argb(0, 246, 22, 219)
srs.points[1].area.foreground_color = Color.from_argb(0, 51, 34, 84)
srs.points[2].area.foreground_color = Color.from_argb(0, 46, 74, 44)
srs.points[3].area.foreground_color = Color.from_argb(0, 19, 99, 44)
srs.points[4].area.foreground_color = Color.from_argb(0, 208, 223, 7)
srs.points[5].area.foreground_color = Color.from_argb(0, 222, 69, 8)
# Autofit all columns
worksheet.auto_fit_columns()
dataDir = dataDir + "output.out.xlsx"
# Save the workbook
workbook.save(dataDir, SaveFormat.XLSX)