Crear un Gráfico de Pastel en Java Programáticamente

Este es otro artículo del blog que demuestra cómo trabajar con gráficos en Java programáticamente. Nuevamente, exploraremos Aspose.Slides para Java e implementaremos cómo crear un gráfico de pastel en Java utilizando los métodos expuestos por esta API de gráficos de pastel. Por lo tanto, este artículo se centrará en la automatización de la creación de gráficos de pastel personalizables que equiparán su software empresarial con un módulo de creador de gráficos de pastel. Por lo tanto, visite esta categoría para aprender sobre las publicaciones del blog que destacan otras características prominentes de Aspose.Slides para Java.

Cubriremos estos puntos:

Instalación de la API de Gráficos de Pastel

La fase de instalación tomará unos segundos. Sin embargo, descargue este archivo JAR o puede usar las configuraciones de Maven.

Instalación de la API de Gráficos de Pastel

Crear un Gráfico de Pastel en Java - Pasos

Los siguientes pasos muestran cómo crear un gráfico de pastel en Java:

  • Instanciar una instancia de la clase Presentation.
  • Acceder a la primera diapositiva llamando al método get_Item.
  • Agregar un gráfico con datos predeterminados llamando al método addChart.
  • Invocar la función getChartDataWorkbook para obtener la hoja de datos del gráfico.
  • Agregar nuevas categorías llamando al método add.
  • Llamar al método addDataPointForPieSeries para poblar los datos de la serie.
  • El getDataPoints().get_Item(0) devolverá el índice (número de serie en esta colección) del punto de datos en esta colección.
  • Establecer el borde del sector llamando al método setFillType.
  • Llamar al método setFirstSliceAngle para establecer el ángulo de rotación para los sectores del gráfico de pastel.
  • Guardar la presentación con el gráfico de pastel llamando al método save.

Código de Ejemplo de Gráfico de Pastel en Java

Ahora, hagamos que el código hable por sí mismo:

// Create a Pie Chart in Java Programmatically
public class Main
{
public static void main(String[] args)
{
// The path to the documents directory.
String dataDir = "/file/";
// Instantiate an instance of the Presentation class.
Presentation presentation = new Presentation();
// Access first slide by calling the get_Item method.
ISlide slides = presentation.getSlides().get_Item(0);
// Add chart with default data by calling the addChart method.
IChart chart = slides.getShapes().addChart(ChartType.Pie, 100, 100, 400, 400);
// Set chart Title, height and some other configurations.
chart.getChartTitle().addTextFrameForOverriding("Sample Title");
chart.getChartTitle().getTextFrameForOverriding().getTextFrameFormat().setCenterText(NullableBool.True);
chart.getChartTitle().setHeight(20);
chart.setTitle(true);
// Set first series to show Values.
chart.getChartData().getSeries().get_Item(0).getLabels().getDefaultDataLabelFormat().setShowValue(true);
// Setting the index of chart data sheet
int defaultWorksheetIndex = 0;
// Invoke the getChartDataWorkbook function to get the chart data worksheet.
IChartDataWorkbook fact = chart.getChartData().getChartDataWorkbook();
// Delete default generated series and categories.
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
// Add new categories by calling the add method.
chart.getChartData().getCategories().add(fact.getCell(0, 1, 0, "First Qtr"));
chart.getChartData().getCategories().add(fact.getCell(0, 2, 0, "2nd Qtr"));
chart.getChartData().getCategories().add(fact.getCell(0, 3, 0, "3rd Qtr"));
// Add new series
IChartSeries series = chart.getChartData().getSeries().add(fact.getCell(0, 0, 1, "Series 1"), chart.getType());
// Call the method to populate series data.
series.getDataPoints().addDataPointForPieSeries(fact.getCell(defaultWorksheetIndex, 1, 1, 20));
series.getDataPoints().addDataPointForPieSeries(fact.getCell(defaultWorksheetIndex, 2, 1, 50));
series.getDataPoints().addDataPointForPieSeries(fact.getCell(defaultWorksheetIndex, 3, 1, 30));
// Not working in new version
// Adding new points and setting sector color
// series.IsColorVaried = true;
chart.getChartData().getSeriesGroups().get_Item(0).setColorVaried(true);
// getDataPoints().get_Item(0) will return index (serial number in this collection) of data point in this collection.
IChartDataPoint point = series.getDataPoints().get_Item(0);
point.getFormat().getFill().setFillType(FillType.Solid);
point.getFormat().getFill().getSolidFillColor().setColor(new Color(PresetColor.Cyan));
// Setting Sector border by calling the setFillType method.
point.getFormat().getLine().getFillFormat().setFillType(FillType.Solid);
point.getFormat().getLine().getFillFormat().getSolidFillColor().setColor(Color.GRAY);
point.getFormat().getLine().setWidth(3.0);
point.getFormat().getLine().setStyle(LineStyle.ThinThick);
point.getFormat().getLine().setDashStyle(LineDashStyle.DashDot);
IChartDataPoint point1 = series.getDataPoints().get_Item(1);
point1.getFormat().getFill().setFillType(FillType.Solid);
point1.getFormat().getFill().getSolidFillColor().setColor(new Color(PresetColor.Brown));
// Setting Sector border
point1.getFormat().getLine().getFillFormat().setFillType(FillType.Solid);
point1.getFormat().getLine().getFillFormat().getSolidFillColor().setColor(Color.BLUE);
point1.getFormat().getLine().setWidth(3.0);
point1.getFormat().getLine().setStyle(LineStyle.Single);
point1.getFormat().getLine().setDashStyle(LineDashStyle.LargeDashDot);
IChartDataPoint point2 = series.getDataPoints().get_Item(2);
point2.getFormat().getFill().setFillType(FillType.Solid);
point2.getFormat().getFill().getSolidFillColor().setColor(new Color(PresetColor.Coral));
// Setting Sector border
point2.getFormat().getLine().getFillFormat().setFillType(FillType.Solid);
point2.getFormat().getLine().getFillFormat().getSolidFillColor().setColor(Color.RED);
point2.getFormat().getLine().setWidth(2.0);
point2.getFormat().getLine().setStyle(LineStyle.ThinThin);
point2.getFormat().getLine().setDashStyle(LineDashStyle.LargeDashDotDot);
// Create custom labels for each of categories for new series
IDataLabel lbl1 = series.getDataPoints().get_Item(0).getLabel();
// lbl.setShowCategoryName(true);
lbl1.getDataLabelFormat().setShowValue(true);
IDataLabel lbl2 = series.getDataPoints().get_Item(1).getLabel();
lbl2.getDataLabelFormat().setShowValue(true);
lbl2.getDataLabelFormat().setShowLegendKey(true);
lbl2.getDataLabelFormat().setShowPercentage(true);
IDataLabel lbl3 = series.getDataPoints().get_Item(2).getLabel();
lbl3.getDataLabelFormat().setShowSeriesName(true);
lbl3.getDataLabelFormat().setShowPercentage(true);
// Showing Leader Lines for Chart
series.getLabels().getDefaultDataLabelFormat().setShowLeaderLines(true);
// Call the setFirstSliceAngle method to set rotation angle for Pie chart sectors.
chart.getChartData().getSeriesGroups().get_Item(0).setFirstSliceAngle(180);
// Save presentation with Pie chart by calling the save method.
presentation.save(dataDir + "PieChart_out.pptx", SaveFormat.Pptx);
}
}
Puedes ver la salida en la imagen a continuación:

Creador de Gráficos de Pastel

Creador de Gráficos de Pastel - Obtén una Licencia Gratuita

Puedes obtener una licencia temporal gratuita para probar esta API de gráficos de pastel sin limitaciones de evaluación.

Resumiendo

Para concluir, esta guía cubrió cómo crear un gráfico de pastel en Java utilizando Aspose.Slides para Java. Además, también revisamos un código de ejemplo de gráfico de pastel en Java para implementar la funcionalidad. Además, puedes navegar a las páginas de documentación, repositorio de GitHub y referencias de API para explorar aún más esta API de gráficos de pastel. Por último, aspose.com escribe continuamente, así que mantente en contacto para las últimas actualizaciones.

No dudes en Ponerte en Contacto

Puedes hacernos saber tus preguntas o consultas en nuestro foro.

Preguntas Frecuentes – FAQs

¿Cómo crear un gráfico de pastel usando Java? Aspose.Slides para Java proporciona un rico conjunto de características para crear gráficos de pastel programáticamente. Sobre todo, visita este enlace para ver los pasos.

¿Cómo crear un gráfico de pastel con datos específicos? Esta sección muestra cómo desarrollar un creador de gráficos de pastel en Java.

Ver También