Crear o actualizar gráficos de presentaciones de PowerPoint en Android
Descripción general
Este artículo describe cómo crear gráficos de presentaciones de PowerPoint en Java. También puedes actualizar los gráficos en Java. Cubre los siguientes temas.
Gráfico: Normal
- Java Crear gráfico de PowerPoint
- Java Crear gráfico de presentación
- Java Crear gráfico de presentación de PowerPoint
Gráfico: Disperso
- Java Crear gráfico disperso
- Java Crear gráfico disperso de PowerPoint
- Java Crear gráfico disperso de presentación de PowerPoint
Gráfico: Circular
- Java Crear gráfico circular
- Java Crear gráfico circular de PowerPoint
- Java Crear gráfico circular de presentación de PowerPoint
Gráfico: Mapa de árbol
- Java Crear gráfico de mapa de árbol
- Java Crear gráfico de mapa de árbol de PowerPoint
- Java Crear gráfico de mapa de árbol de presentación de PowerPoint
Gráfico: Acciones
- Java Crear gráfico de acciones
- Java Crear gráfico de acciones de PowerPoint
- Java Crear gráfico de acciones de presentación de PowerPoint
Gráfico: Caja y bigote
- Java Crear gráfico de caja y bigote
- Java Crear gráfico de caja y bigote de PowerPoint
- Java Crear gráfico de caja y bigote de presentación de PowerPoint
Gráfico: Embudo
- Java Crear gráfico de embudo
- Java Crear gráfico de embudo de PowerPoint
- Java Crear gráfico de embudo de presentación de PowerPoint
Gráfico: Ráfaga
- Java Crear gráfico de ráfaga
- Java Crear gráfico de ráfaga de PowerPoint
- Java Crear gráfico de ráfaga de presentación de PowerPoint
Gráfico: Histograma
- Java Crear histograma
- Java Crear histograma de PowerPoint
- Java Crear histograma de presentación de PowerPoint
Gráfico: Radar
- Java Crear gráfico radar
- Java Crear gráfico radar de PowerPoint
- Java Crear gráfico radar de presentación de PowerPoint
Gráfico: Multi categoría
- Java Crear gráfico multi categoría
- Java Crear gráfico multi categoría de PowerPoint
- Java Crear gráfico multi categoría de presentación de PowerPoint
Gráfico: Mapa
- Java Crear gráfico de mapa
- Java Crear gráfico de mapa de PowerPoint
- Java Crear gráfico de mapa de presentación de PowerPoint
Acción: Actualizar gráfico
- Java Actualizar gráfico de PowerPoint
- Java Actualizar gráfico de presentación
- Java Actualizar gráfico de presentación de PowerPoint
Crear un gráfico
Los gráficos ayudan a las personas a visualizar datos rápidamente y obtener ideas, lo que puede no ser evidente a partir de una tabla o una hoja de cálculo.
¿Por qué crear gráficos?
Con los gráficos, puedes
- agregar, condensar o resumir grandes cantidades de datos en una sola diapositiva de una presentación
- mostrar patrones y tendencias en los datos
- deducir la dirección y el impulso de los datos a lo largo del tiempo o respecto a una unidad de medida específica
- detectar valores atípicos, aberraciones, desviaciones, errores, datos sin sentido, etc.
- comunicar o presentar datos complejos
En PowerPoint, puedes crear gráficos mediante la función de inserción, que proporciona plantillas para diseñar muchos tipos de gráficos. Con Aspose.Slides, puedes crear gráficos habituales (basados en tipos de gráfico populares) y gráficos personalizados.
Crear gráficos normales
Pasos: Crear gráfico
- Pasos: Crear gráfico de PowerPoint en Java
- Pasos: Crear gráfico de presentación en Java
- Pasos: Crear gráfico de presentación de PowerPoint en Java
Pasos de código:
- Crea una instancia de la clase Presentation.
- Obtén una referencia a una diapositiva mediante su índice.
- Añade un gráfico con algunos datos y especifica el tipo de gráfico que prefieras.
- Añade un título para el gráfico.
- Accede a la hoja de datos del gráfico.
- Elimina todas las series y categorías predeterminadas.
- Añade nuevas series y categorías.
- Añade algunos datos nuevos para las series del gráfico.
- Añade un color de relleno para las series del gráfico.
- Añade etiquetas para las series del gráfico.
- Guarda la presentación modificada como un archivo PPTX.
Este código Java muestra cómo crear un gráfico normal:
// Instancia una clase de presentación que representa un archivo PPTX
Presentation pres = new Presentation();
try {
// Accede a la primera diapositiva
ISlide sld = pres.getSlides().get_Item(0);
// Añade un gráfico con sus datos predeterminados
IChart chart = sld.getShapes().addChart(ChartType.ClusteredColumn, 0, 0, 500, 500);
// Establece el título del gráfico
chart.getChartTitle().addTextFrameForOverriding("Sample Title");
chart.getChartTitle().getTextFrameForOverriding().getTextFrameFormat().setCenterText(NullableBool.True);
chart.getChartTitle().setHeight(20);
chart.hasTitle();
// Configura la primera serie para mostrar valores
chart.getChartData().getSeries().get_Item(0).getLabels().getDefaultDataLabelFormat().setShowValue(true);
// Establece el índice de la hoja de datos del gráfico
int defaultWorksheetIndex = 0;
// Obtiene la hoja de datos del gráfico
IChartDataWorkbook fact = chart.getChartData().getChartDataWorkbook();
// Elimina las series y categorías generadas por defecto
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
int s = chart.getChartData().getSeries().size();
s = chart.getChartData().getCategories().size();
// Añade nuevas series
chart.getChartData().getSeries().add(fact.getCell(defaultWorksheetIndex, 0, 1, "Series 1"),chart.getType());
chart.getChartData().getSeries().add(fact.getCell(defaultWorksheetIndex, 0, 2, "Series 2"),chart.getType());
// Añade nuevas categorías
chart.getChartData().getCategories().add(fact.getCell(defaultWorksheetIndex, 1, 0, "Caetegoty 1"));
chart.getChartData().getCategories().add(fact.getCell(defaultWorksheetIndex, 2, 0, "Caetegoty 2"));
chart.getChartData().getCategories().add(fact.getCell(defaultWorksheetIndex, 3, 0, "Caetegoty 3"));
// Toma la primera serie del gráfico
IChartSeries series = chart.getChartData().getSeries().get_Item(0);
// Ahora rellena los datos de la serie
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, 1, 1, 20));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, 2, 1, 50));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, 3, 1, 30));
// Establece el color de relleno para la serie
series.getFormat().getFill().setFillType(FillType.Solid);
series.getFormat().getFill().getSolidFillColor().setColor(Color.RED);
// Toma la segunda serie del gráfico
series = chart.getChartData().getSeries().get_Item(1);
// Rellena los datos de la serie
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, 1, 2, 30));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, 2, 2, 10));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, 3, 2, 60));
// Establece el color de relleno para la serie
series.getFormat().getFill().setFillType(FillType.Solid);
series.getFormat().getFill().getSolidFillColor().setColor(Color.GREEN);
// Crea etiquetas personalizadas para cada categoría de la nueva serie
// Establece la primera etiqueta para mostrar el nombre de la categoría
IDataLabel lbl = series.getDataPoints().get_Item(0).getLabel();
lbl.getDataLabelFormat().setShowCategoryName(true);
lbl = series.getDataPoints().get_Item(1).getLabel();
lbl.getDataLabelFormat().setShowSeriesName(true);
// Muestra el valor para la tercera etiqueta
lbl = series.getDataPoints().get_Item(2).getLabel();
lbl.getDataLabelFormat().setShowValue(true);
lbl.getDataLabelFormat().setShowSeriesName(true);
lbl.getDataLabelFormat().setSeparator("/");
// Guarda la presentación con el gráfico
pres.save("output.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear gráficos dispersos
Los gráficos dispersos (también conocidos como diagramas de dispersión o gráficos x‑y) se usan a menudo para comprobar patrones o demostrar correlaciones entre dos variables.
Puedes necesitar un gráfico disperso cuando
- tienes datos numéricos pareados
- tienes 2 variables que se relacionan bien entre sí
- deseas determinar si 2 variables están relacionadas
- tienes una variable independiente que tiene múltiples valores para una variable dependiente
Pasos: Crear gráfico disperso en Java | Pasos: Crear gráfico disperso de PowerPoint en Java | Pasos: Crear gráfico disperso de presentación de PowerPoint en Java
- Por favor, sigue los pasos mencionados arriba en Crear gráficos normales
- Para el tercer paso, añade un gráfico con algunos datos y especifica tu tipo de gráfico como uno de los siguientes
- ChartType.ScatterWithMarkers - Representa un gráfico de dispersión.
- ChartType.ScatterWithSmoothLinesAndMarkers - Representa un gráfico de dispersión conectado por curvas, con marcadores de datos.
- ChartType.ScatterWithSmoothLines - Representa un gráfico de dispersión conectado por curvas, sin marcadores de datos.
- ChartType.ScatterWithStraightLinesAndMarkers - Representa un gráfico de dispersión conectado por líneas, con marcadores de datos.
- ChartType.ScatterWithStraightLines - Representa un gráfico de dispersión conectado por líneas, sin marcadores de datos.
Este código Java muestra cómo crear gráficos dispersos con diferentes series de marcadores:
// Instancia una clase de presentación que representa un archivo PPTX
Presentation pres = new Presentation();
try {
// Accede a la primera diapositiva
ISlide slide = pres.getSlides().get_Item(0);
// Crea el gráfico predeterminado
IChart chart = slide.getShapes().addChart(ChartType.ScatterWithSmoothLines, 0, 0, 400, 400);
// Obtiene el índice de la hoja de datos del gráfico predeterminado
int defaultWorksheetIndex = 0;
// Obtiene la hoja de datos del gráfico
IChartDataWorkbook fact = chart.getChartData().getChartDataWorkbook();
// Elimina la serie de demostración
chart.getChartData().getSeries().clear();
// Añade nuevas series
chart.getChartData().getSeries().add(fact.getCell(defaultWorksheetIndex, 1, 1, "Series 1"), chart.getType());
chart.getChartData().getSeries().add(fact.getCell(defaultWorksheetIndex, 1, 3, "Series 2"), chart.getType());
// Obtiene la primera serie del gráfico
IChartSeries series = chart.getChartData().getSeries().get_Item(0);
// Añade un nuevo punto (1:3) a la serie
series.getDataPoints().addDataPointForScatterSeries(fact.getCell(defaultWorksheetIndex, 2, 1, 1), fact.getCell(defaultWorksheetIndex, 2, 2, 3));
// Añade un nuevo punto (2:10)
series.getDataPoints().addDataPointForScatterSeries(fact.getCell(defaultWorksheetIndex, 3, 1, 2), fact.getCell(defaultWorksheetIndex, 3, 2, 10));
// Cambia el tipo de serie
series.setType(ChartType.ScatterWithStraightLinesAndMarkers);
// Cambia el marcador de la serie del gráfico
series.getMarker().setSize(10);
series.getMarker().setSymbol(MarkerStyleType.Star);
// Obtiene la segunda serie del gráfico
series = chart.getChartData().getSeries().get_Item(1);
// Añade un nuevo punto (5:2) allí
series.getDataPoints().addDataPointForScatterSeries(fact.getCell(defaultWorksheetIndex, 2, 3, 5), fact.getCell(defaultWorksheetIndex, 2, 4, 2));
// Añade un nuevo punto (3:1)
series.getDataPoints().addDataPointForScatterSeries(fact.getCell(defaultWorksheetIndex, 3, 3, 3), fact.getCell(defaultWorksheetIndex, 3, 4, 1));
// Añade un nuevo punto (2:2)
series.getDataPoints().addDataPointForScatterSeries(fact.getCell(defaultWorksheetIndex, 4, 3, 2), fact.getCell(defaultWorksheetIndex, 4, 4, 2));
// Añade un nuevo punto (5:1)
series.getDataPoints().addDataPointForScatterSeries(fact.getCell(defaultWorksheetIndex, 5, 3, 5), fact.getCell(defaultWorksheetIndex, 5, 4, 1));
// Cambia el marcador de la serie del gráfico
series.getMarker().setSize(10);
series.getMarker().setSymbol(MarkerStyleType.Circle);
pres.save("AsposeChart_out.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear gráficos circulares
Los gráficos circulares se usan mejor para mostrar la relación parte‑a‑todo en los datos, especialmente cuando los datos contienen etiquetas categóricas con valores numéricos. Sin embargo, si tus datos contienen muchas partes o etiquetas, podrías considerar usar un gráfico de barras en su lugar.
Pasos: Crear gráfico circular en Java | Pasos: Crear gráfico circular de PowerPoint en Java | Pasos: Crear gráfico circular de presentación de PowerPoint en Java
- Crea una instancia de la clase Presentation.
- Obtén una referencia a una diapositiva mediante su índice.
- Añade un gráfico con datos predeterminados y el tipo deseado (en este caso, ChartType.Pie).
- Accede a los datos del gráfico mediante IChartDataWorkbook.
- Elimina las series y categorías predeterminadas.
- Añade nuevas series y categorías.
- Añade nuevos datos para las series del gráfico.
- Añade nuevos puntos y colores personalizados para los sectores del gráfico circular.
- Establece etiquetas para las series.
- Establece líneas guía para las etiquetas de series.
- Establece el ángulo de rotación para las diapositivas del gráfico circular.
- Guarda la presentación modificada como un archivo PPTX.
Este código Java muestra cómo crear un gráfico circular:
// Instancia una clase de presentación que representa un archivo PPTX
Presentation pres = new Presentation();
try {
// Accede a la primera diapositiva
ISlide slides = pres.getSlides().get_Item(0);
// Añade un gráfico con datos predeterminados
IChart chart = slides.getShapes().addChart(ChartType.Pie, 100, 100, 400, 400);
// Establece el título del gráfico
chart.getChartTitle().addTextFrameForOverriding("Sample Title");
chart.getChartTitle().getTextFrameForOverriding().getTextFrameFormat().setCenterText(NullableBool.True);
chart.getChartTitle().setHeight(20);
chart.setTitle(true);
// Configura la primera serie para mostrar valores
chart.getChartData().getSeries().get_Item(0).getLabels().getDefaultDataLabelFormat().setShowValue(true);
// Establece el índice de la hoja de datos del gráfico
int defaultWorksheetIndex = 0;
// Obtiene la hoja de datos del gráfico
IChartDataWorkbook fact = chart.getChartData().getChartDataWorkbook();
// Elimina las series y categorías generadas por defecto
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
// Añade nuevas categorías
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"));
// Añade nuevas series
IChartSeries series = chart.getChartData().getSeries().add(fact.getCell(0, 0, 1, "Series 1"), chart.getType());
//Puebla los datos de la serie
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));
// No funciona en la nueva versión
// Añadiendo nuevos puntos y estableciendo el color del sector
// series.IsColorVaried = true;
chart.getChartData().getSeriesGroups().get_Item(0).setColorVaried(true);
IChartDataPoint point = series.getDataPoints().get_Item(0);
point.getFormat().getFill().setFillType(FillType.Solid);
point.getFormat().getFill().getSolidFillColor().setColor(Color.CYAN);
// Establece el borde del sector
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(Color.ORANGE);
// Establece el borde del sector
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(Color.YELLOW);
// Establece el borde del sector
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);
// Crea etiquetas personalizadas para cada categoría de la nueva serie
IDataLabel lbl1 = series.getDataPoints().get_Item(0).getLabel();
// lbl.ShowCategoryName = 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);
// Muestra líneas guía para el gráfico
series.getLabels().getDefaultDataLabelFormat().setShowLeaderLines(true);
// Establece el ángulo de rotación para los sectores del gráfico circular
chart.getChartData().getSeriesGroups().get_Item(0).setFirstSliceAngle(180);
// Guarda la presentación con un gráfico
pres.save("PieChart_out.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear gráficos de líneas
Los gráficos de líneas (también conocidos como diagramas de líneas) se usan mejor cuando deseas demostrar cambios de valor a lo largo del tiempo. Con un gráfico de líneas, puedes comparar muchos datos a la vez, seguir cambios y tendencias a lo largo del tiempo, resaltar anomalías en series de datos, etc.
- Crea una instancia de la clase Presentation.
- Obtén una referencia a una diapositiva mediante su índice.
- Añade un gráfico con datos predeterminados y el tipo deseado (en este caso,
ChartType.Line). - Accede a los datos del gráfico mediante IChartDataWorkbook.
- Elimina las series y categorías predeterminadas.
- Añade nuevas series y categorías.
- Añade nuevos datos para las series del gráfico.
- Guarda la presentación modificada como un archivo PPTX.
Este código Java muestra cómo crear un gráfico de líneas:
Presentation pres = new Presentation();
try {
IChart lineChart = pres.getSlides().get_Item(0).getShapes().addChart(ChartType.Line, 10, 50, 600, 350);
pres.save("lineChart.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Por defecto, los puntos de un gráfico de líneas están unidos por líneas continuas rectas. Si deseas que los puntos se unan mediante guiones, puedes especificar tu tipo de guión preferido así:
IChart lineChart = pres.getSlides().get_Item(0).getShapes().addChart(ChartType.Line, 10, 50, 600, 350);
for (IChartSeries series : lineChart.getChartData().getSeries())
{
series.getFormat().getLine().setDashStyle(LineDashStyle.Dash);
}
Crear gráficos de mapa de árbol
Los gráficos de mapa de árbol se usan mejor para datos de ventas cuando deseas mostrar el tamaño relativo de las categorías de datos y (al mismo tiempo) llamar rápidamente la atención sobre los elementos que aportan más a cada categoría.
Pasos: Crear gráfico de mapa de árbol en Java | Pasos: Crear gráfico de mapa de árbol de PowerPoint en Java | Pasos: Crear gráfico de mapa de árbol de presentación de PowerPoint en Java
- Crea una instancia de la clase Presentation .
- Obtén una referencia a una diapositiva mediante su índice.
- Añade un gráfico con datos predeterminados y el tipo deseado (en este caso, ChartType.TreeMap).
- Accede a los datos del gráfico mediante IChartDataWorkbook.
- Elimina las series y categorías predeterminadas.
- Añade nuevas series y categorías.
- Añade nuevos datos para las series del gráfico.
- Guarda la presentación modificada como un archivo PPTX.
Este código Java muestra cómo crear un gráfico de mapa de árbol:
Presentation pres = new Presentation();
try {
IChart chart = pres.getSlides().get_Item(0).getShapes().addChart(ChartType.Treemap, 50, 50, 500, 400);
chart.getChartData().getCategories().clear();
chart.getChartData().getSeries().clear();
IChartDataWorkbook wb = chart.getChartData().getChartDataWorkbook();
wb.clear(0);
//rama 1
IChartCategory leaf = chart.getChartData().getCategories().add(wb.getCell(0, "C1", "Leaf1"));
leaf.getGroupingLevels().setGroupingItem(1, "Stem1");
leaf.getGroupingLevels().setGroupingItem(2, "Branch1");
chart.getChartData().getCategories().add(wb.getCell(0, "C2", "Leaf2"));
leaf = chart.getChartData().getCategories().add(wb.getCell(0, "C3", "Leaf3"));
leaf.getGroupingLevels().setGroupingItem(1, "Stem2");
chart.getChartData().getCategories().add(wb.getCell(0, "C4", "Leaf4"));
//rama 2
leaf = chart.getChartData().getCategories().add(wb.getCell(0, "C5", "Leaf5"));
leaf.getGroupingLevels().setGroupingItem(1, "Stem3");
leaf.getGroupingLevels().setGroupingItem(2, "Branch2");
chart.getChartData().getCategories().add(wb.getCell(0, "C6", "Leaf6"));
leaf = chart.getChartData().getCategories().add(wb.getCell(0, "C7", "Leaf7"));
leaf.getGroupingLevels().setGroupingItem(1, "Stem4");
chart.getChartData().getCategories().add(wb.getCell(0, "C8", "Leaf8"));
IChartSeries series = chart.getChartData().getSeries().add(ChartType.Treemap);
series.getLabels().getDefaultDataLabelFormat().setShowCategoryName(true);
series.getDataPoints().addDataPointForTreemapSeries(wb.getCell(0, "D1", 4));
series.getDataPoints().addDataPointForTreemapSeries(wb.getCell(0, "D2", 5));
series.getDataPoints().addDataPointForTreemapSeries(wb.getCell(0, "D3", 3));
series.getDataPoints().addDataPointForTreemapSeries(wb.getCell(0, "D4", 6));
series.getDataPoints().addDataPointForTreemapSeries(wb.getCell(0, "D5", 9));
series.getDataPoints().addDataPointForTreemapSeries(wb.getCell(0, "D6", 9));
series.getDataPoints().addDataPointForTreemapSeries(wb.getCell(0, "D7", 4));
series.getDataPoints().addDataPointForTreemapSeries(wb.getCell(0, "D8", 3));
series.setParentLabelLayout(ParentLabelLayoutType.Overlapping);
pres.save("Treemap.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear gráficos de acciones
Pasos: Crear gráfico de acciones en Java | Pasos: Crear gráfico de acciones de PowerPoint en Java | Pasos: Crear gráfico de acciones de presentación de PowerPoint en Java
- Crea una instancia de la clase Presentation .
- Obtén una referencia a una diapositiva mediante su índice.
- Añade un gráfico con datos predeterminados y el tipo deseado (ChartType.OpenHighLowClose).
- Accede a los datos del gráfico mediante IChartDataWorkbook.
- Elimina las series y categorías predeterminadas.
- Añade nuevas series y categorías.
- Añade nuevos datos para las series del gráfico.
- Especifica el formato HiLowLines.
- Guarda la presentación modificada como un archivo PPTX
Ejemplo de código Java usado para crear un gráfico de acciones:
Presentation pres = new Presentation();
try {
IChart chart = pres.getSlides().get_Item(0).getShapes().addChart(ChartType.OpenHighLowClose, 50, 50, 600, 400, false);
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
IChartDataWorkbook wb = chart.getChartData().getChartDataWorkbook();
chart.getChartData().getCategories().add(wb.getCell(0, 1, 0, "A"));
chart.getChartData().getCategories().add(wb.getCell(0, 2, 0, "B"));
chart.getChartData().getCategories().add(wb.getCell(0, 3, 0, "C"));
chart.getChartData().getSeries().add(wb.getCell(0, 0, 1, "Open"), chart.getType());
chart.getChartData().getSeries().add(wb.getCell(0, 0, 2, "High"), chart.getType());
chart.getChartData().getSeries().add(wb.getCell(0, 0, 3, "Low"), chart.getType());
chart.getChartData().getSeries().add(wb.getCell(0, 0, 4, "Close"), chart.getType());
IChartSeries series = chart.getChartData().getSeries().get_Item(0);
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 1, 1, 72));
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 2, 1, 25));
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 3, 1, 38));
series = chart.getChartData().getSeries().get_Item(1);
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 1, 2, 172));
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 2, 2, 57));
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 3, 2, 57));
series = chart.getChartData().getSeries().get_Item(2);
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 1, 3, 12));
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 2, 3, 12));
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 3, 3, 13));
series = chart.getChartData().getSeries().get_Item(3);
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 1, 4, 25));
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 2, 4, 38));
series.getDataPoints().addDataPointForStockSeries(wb.getCell(0, 3, 4, 50));
chart.getChartData().getSeriesGroups().get_Item(0).getUpDownBars().setUpDownBars(true);
chart.getChartData().getSeriesGroups().get_Item(0).getHiLowLinesFormat().getLine().getFillFormat().setFillType(FillType.Solid);
for (IChartSeries ser : chart.getChartData().getSeries())
{
ser.getFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
}
pres.save("output.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear gráficos de caja y bigote
Pasos: Crear gráfico de caja y bigote en Java | Pasos: Crear gráfico de caja y bigote de PowerPoint en Java | Pasos: Crear gráfico de caja y bigote de presentación de PowerPoint en Java
- Crea una instancia de la clase Presentation .
- Obtén una referencia a una diapositiva mediante su índice.
- Añade un gráfico con datos predeterminados y el tipo deseado (ChartType.BoxAndWhisker).
- Accede a los datos del gráfico mediante IChartDataWorkbook.
- Elimina las series y categorías predeterminadas.
- Añade nuevas series y categorías.
- Añade nuevos datos para las series del gráfico.
- Guarda la presentación modificada como un archivo PPTX
Este código Java muestra cómo crear un gráfico de caja y bigote:
Presentation pres = new Presentation();
try {
IChart chart = pres.getSlides().get_Item(0).getShapes().addChart(ChartType.BoxAndWhisker, 50, 50, 500, 400);
chart.getChartData().getCategories().clear();
chart.getChartData().getSeries().clear();
IChartDataWorkbook wb = chart.getChartData().getChartDataWorkbook();
wb.clear(0);
chart.getChartData().getCategories().add(wb.getCell(0, "A1", "Category 1"));
chart.getChartData().getCategories().add(wb.getCell(0, "A2", "Category 1"));
chart.getChartData().getCategories().add(wb.getCell(0, "A3", "Category 1"));
chart.getChartData().getCategories().add(wb.getCell(0, "A4", "Category 1"));
chart.getChartData().getCategories().add(wb.getCell(0, "A5", "Category 1"));
chart.getChartData().getCategories().add(wb.getCell(0, "A6", "Category 1"));
IChartSeries series = chart.getChartData().getSeries().add(ChartType.BoxAndWhisker);
series.setQuartileMethod(QuartileMethodType.Exclusive);
series.setShowMeanLine(true);
series.setShowMeanMarkers(true);
series.setShowInnerPoints(true);
series.setShowOutlierPoints(true);
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(wb.getCell(0, "B1", 15));
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(wb.getCell(0, "B2", 41));
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(wb.getCell(0, "B3", 16));
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(wb.getCell(0, "B4", 10));
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(wb.getCell(0, "B5", 23));
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(wb.getCell(0, "B6", 16));
pres.save("BoxAndWhisker.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear gráficos de embudo
Pasos: Crear gráfico de embudo en Java | Pasos: Crear gráfico de embudo de PowerPoint en Java | Pasos: Crear gráfico de embudo de presentación de PowerPoint en Java
- Crea una instancia de la clase Presentation .
- Obtén una referencia a una diapositiva mediante su índice.
- Añade un gráfico con datos predeterminados y el tipo deseado (ChartType.Funnel).
- Guarda la presentación modificada como un archivo PPTX
El código Java muestra cómo crear un gráfico de embudo:
Presentation pres = new Presentation();
try {
IChart chart = pres.getSlides().get_Item(0).getShapes().addChart(ChartType.Funnel, 50, 50, 500, 400);
chart.getChartData().getCategories().clear();
chart.getChartData().getSeries().clear();
IChartDataWorkbook wb = chart.getChartData().getChartDataWorkbook();
wb.clear(0);
chart.getChartData().getCategories().add(wb.getCell(0, "A1", "Category 1"));
chart.getChartData().getCategories().add(wb.getCell(0, "A2", "Category 2"));
chart.getChartData().getCategories().add(wb.getCell(0, "A3", "Category 3"));
chart.getChartData().getCategories().add(wb.getCell(0, "A4", "Category 4"));
chart.getChartData().getCategories().add(wb.getCell(0, "A5", "Category 5"));
chart.getChartData().getCategories().add(wb.getCell(0, "A6", "Category 6"));
IChartSeries series = chart.getChartData().getSeries().add(ChartType.Funnel);
series.getDataPoints().addDataPointForFunnelSeries(wb.getCell(0, "B1", 50));
series.getDataPoints().addDataPointForFunnelSeries(wb.getCell(0, "B2", 100));
series.getDataPoints().addDataPointForFunnelSeries(wb.getCell(0, "B3", 200));
series.getDataPoints().addDataPointForFunnelSeries(wb.getCell(0, "B4", 300));
series.getDataPoints().addDataPointForFunnelSeries(wb.getCell(0, "B5", 400));
series.getDataPoints().addDataPointForFunnelSeries(wb.getCell(0, "B6", 500));
pres.save("Funnel.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear gráficos de ráfaga
Pasos: Crear gráfico de ráfaga en Java | Pasos: Crear gráfico de ráfaga de PowerPoint en Java | Pasos: Crear gráfico de ráfaga de presentación de PowerPoint en Java
- Crea una instancia de la clase Presentation .
- Obtén una referencia a una diapositiva mediante su índice.
- Añade un gráfico con datos predeterminados y el tipo deseado (en este caso, ChartType.sunburst).
- Guarda la presentación modificada como un archivo PPTX
Este código Java muestra cómo crear un gráfico de ráfaga:
Presentation pres = new Presentation();
try {
IChart chart = pres.getSlides().get_Item(0).getShapes().addChart(ChartType.Sunburst, 50, 50, 500, 400);
chart.getChartData().getCategories().clear();
chart.getChartData().getSeries().clear();
IChartDataWorkbook wb = chart.getChartData().getChartDataWorkbook();
wb.clear(0);
//rama 1
IChartCategory leaf = chart.getChartData().getCategories().add(wb.getCell(0, "C1", "Leaf1"));
leaf.getGroupingLevels().setGroupingItem(1, "Stem1");
leaf.getGroupingLevels().setGroupingItem(2, "Branch1");
chart.getChartData().getCategories().add(wb.getCell(0, "C2", "Leaf2"));
leaf = chart.getChartData().getCategories().add(wb.getCell(0, "C3", "Leaf3"));
leaf.getGroupingLevels().setGroupingItem(1, "Stem2");
chart.getChartData().getCategories().add(wb.getCell(0, "C4", "Leaf4"));
//rama 2
leaf = chart.getChartData().getCategories().add(wb.getCell(0, "C5", "Leaf5"));
leaf.getGroupingLevels().setGroupingItem(1, "Stem3");
leaf.getGroupingLevels().setGroupingItem(2, "Branch2");
chart.getChartData().getCategories().add(wb.getCell(0, "C6", "Leaf6"));
leaf = chart.getChartData().getCategories().add(wb.getCell(0, "C7", "Leaf7"));
leaf.getGroupingLevels().setGroupingItem(1, "Stem4");
chart.getChartData().getCategories().add(wb.getCell(0, "C8", "Leaf8"));
IChartSeries series = chart.getChartData().getSeries().add(ChartType.Sunburst);
series.getLabels().getDefaultDataLabelFormat().setShowCategoryName(true);
series.getDataPoints().addDataPointForSunburstSeries(wb.getCell(0, "D1", 4));
series.getDataPoints().addDataPointForSunburstSeries(wb.getCell(0, "D2", 5));
series.getDataPoints().addDataPointForSunburstSeries(wb.getCell(0, "D3", 3));
series.getDataPoints().addDataPointForSunburstSeries(wb.getCell(0, "D4", 6));
series.getDataPoints().addDataPointForSunburstSeries(wb.getCell(0, "D5", 9));
series.getDataPoints().addDataPointForSunburstSeries(wb.getCell(0, "D6", 9));
series.getDataPoints().addDataPointForSunburstSeries(wb.getCell(0, "D7", 4));
series.getDataPoints().addDataPointForSunburstSeries(wb.getCell(0, "D8", 3));
pres.save("Sunburst.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear histogramas
Pasos: Crear histograma en Java | Pasos: Crear histograma de PowerPoint en Java | Pasos: Crear histograma de presentación de PowerPoint en Java
- Crea una instancia de la clase Presentation .
- Obtén una referencia a una diapositiva mediante su índice.
- Añade un gráfico con datos predeterminados y el tipo deseado (ChartType.Histogram).
- Accede a los datos del gráfico mediante IChartDataWorkbook.
- Elimina las series y categorías predeterminadas.
- Añade nuevas series y categorías.
- Guarda la presentación modificada como un archivo PPTX
Este código Java muestra cómo crear un histograma:
Presentation pres = new Presentation();
try {
IChart chart = pres.getSlides().get_Item(0).getShapes().addChart(ChartType.Histogram, 50, 50, 500, 400);
chart.getChartData().getCategories().clear();
chart.getChartData().getSeries().clear();
IChartDataWorkbook wb = chart.getChartData().getChartDataWorkbook();
wb.clear(0);
IChartSeries series = chart.getChartData().getSeries().add(ChartType.Histogram);
series.getDataPoints().addDataPointForHistogramSeries(wb.getCell(0, "A1", 15));
series.getDataPoints().addDataPointForHistogramSeries(wb.getCell(0, "A2", -41));
series.getDataPoints().addDataPointForHistogramSeries(wb.getCell(0, "A3", 16));
series.getDataPoints().addDataPointForHistogramSeries(wb.getCell(0, "A4", 10));
series.getDataPoints().addDataPointForHistogramSeries(wb.getCell(0, "A5", -23));
series.getDataPoints().addDataPointForHistogramSeries(wb.getCell(0, "A6", 16));
chart.getAxes().getHorizontalAxis().setAggregationType(AxisAggregationType.Automatic;)
pres.save("Histogram.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear gráficos radar
Pasos: Crear gráfico radar en Java | Pasos: Crear gráfico radar de PowerPoint en Java | Pasos: Crear gráfico radar de presentación de PowerPoint en Java
- Crea una instancia de la clase Presentation .
- Obtén una referencia a una diapositiva mediante su índice.
- Añade un gráfico con algunos datos y especifica tu tipo de gráfico preferido (
ChartType.Radaren este caso). - Guarda la presentación modificada como un archivo PPTX
Este código Java muestra cómo crear un gráfico radar:
Presentation pres = new Presentation();
try {
pres.getSlides().get_Item(0).getShapes().addChart(ChartType.Radar, 20, 20, 400, 300);
pres.save("Radar-chart.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear gráficos multi categoría
Pasos: Crear gráfico multi categoría en Java | Pasos: Crear gráfico multi categoría de PowerPoint en Java | Pasos: Crear gráfico multi categoría de presentación de PowerPoint en Java
- Crea una instancia de la clase Presentation .
- Obtén una referencia a una diapositiva mediante su índice.
- Añade un gráfico con datos predeterminados y el tipo deseado (ChartType.ClusteredColumn).
- Accede a los datos del gráfico mediante IChartDataWorkbook.
- Elimina las series y categorías predeterminadas.
- Añade nuevas series y categorías.
- Añade nuevos datos para las series del gráfico.
- Guarda la presentación modificada como un archivo PPTX.
Este código Java muestra cómo crear un gráfico multi categoría:
Presentation pres = new Presentation();
try {
IChart ch = pres.getSlides().get_Item(0).getShapes().addChart(ChartType.ClusteredColumn, 100, 100, 600, 450);
ch.getChartData().getSeries().clear();
ch.getChartData().getCategories().clear();
IChartDataWorkbook fact = ch.getChartData().getChartDataWorkbook();
fact.clear(0);
int defaultWorksheetIndex = 0;
IChartCategory category = ch.getChartData().getCategories().add(fact.getCell(0, "c2", "A"));
category.getGroupingLevels().setGroupingItem(1, "Group1");
category = ch.getChartData().getCategories().add(fact.getCell(0, "c3", "B"));
category = ch.getChartData().getCategories().add(fact.getCell(0, "c4", "C"));
category.getGroupingLevels().setGroupingItem(1, "Group2");
category = ch.getChartData().getCategories().add(fact.getCell(0, "c5", "D"));
category = ch.getChartData().getCategories().add(fact.getCell(0, "c6", "E"));
category.getGroupingLevels().setGroupingItem(1, "Group3");
category = ch.getChartData().getCategories().add(fact.getCell(0, "c7", "F"));
category = ch.getChartData().getCategories().add(fact.getCell(0, "c8", "G"));
category.getGroupingLevels().setGroupingItem(1, "Group4");
category = ch.getChartData().getCategories().add(fact.getCell(0, "c9", "H"));
// Añadiendo series
IChartSeries series = ch.getChartData().getSeries().add(fact.getCell(0, "D1", "Series 1"),
ChartType.ClusteredColumn);
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, "D2", 10));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, "D3", 20));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, "D4", 30));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, "D5", 40));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, "D6", 50));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, "D7", 60));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, "D8", 70));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, "D9", 80));
// Guardar presentación con gráfico
pres.save("AsposeChart_out.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear gráficos de mapa
Un gráfico de mapa es una visualización de un área que contiene datos. Los gráficos de mapa se utilizan mejor para comparar datos o valores a través de regiones geográficas.
Pasos: Crear gráfico de mapa en Java | Pasos: Crear gráfico de mapa de PowerPoint en Java | Pasos: Crear gráfico de mapa de presentación de PowerPoint en Java
Este código Java muestra cómo crear un gráfico de mapa:
Presentation pres = new Presentation();
try {
IChart chart = pres.getSlides().get_Item(0).getShapes().addChart(ChartType.Map, 50, 50, 500, 400);
pres.save("mapChart.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Crear gráficos combinados
Un gráfico combinado (o gráfico combo) combina dos o más tipos de gráfico en un solo diagrama. Este gráfico te permite resaltar, comparar o examinar diferencias entre dos o más conjuntos de datos, ayudándote a identificar relaciones entre ellos.

El siguiente código Java muestra cómo crear el gráfico combinado mostrado arriba en una presentación de PowerPoint:
static void createComboChart() {
Presentation presentation = new Presentation();
ISlide slide = presentation.getSlides().get_Item(0);
try {
IChart chart = createChartWithFirstSeries(slide);
addSecondSeriesToChart(chart);
addThirdSeriesToChart(chart);
setPrimaryAxesFormat(chart);
setSecondaryAxesFormat(chart);
presentation.save("combo-chart.pptx", SaveFormat.Pptx);
} finally {
presentation.dispose();
}
}
static IChart createChartWithFirstSeries(ISlide slide) {
IChart chart = slide.getShapes().addChart(ChartType.ClusteredColumn, 50, 50, 600, 400);
// Set the chart title.
chart.setTitle(true);
chart.getChartTitle().addTextFrameForOverriding("Chart Title");
chart.getChartTitle().setOverlay(false);
IParagraph titleParagraph = chart.getChartTitle().getTextFrameForOverriding().getParagraphs().get_Item(0);
IPortionFormat titleFormat = titleParagraph.getParagraphFormat().getDefaultPortionFormat();
titleFormat.setFontBold(NullableBool.False);
titleFormat.setFontHeight(18f);
// Set the chart legend.
chart.getLegend().setPosition(LegendPositionType.Bottom);
chart.getLegend().getTextFormat().getPortionFormat().setFontHeight(12f);
// Delete the default generated series and categories.
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
int worksheetIndex = 0;
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
// Add new categories.
chart.getChartData().getCategories().add(workbook.getCell(worksheetIndex, 1, 0, "Category 1"));
chart.getChartData().getCategories().add(workbook.getCell(worksheetIndex, 2, 0, "Category 2"));
chart.getChartData().getCategories().add(workbook.getCell(worksheetIndex, 3, 0, "Category 3"));
chart.getChartData().getCategories().add(workbook.getCell(worksheetIndex, 4, 0, "Category 4"));
// Add the first series.
IChartDataCell seriesNameCell = workbook.getCell(worksheetIndex, 0, 1, "Series 1");
IChartSeries series = chart.getChartData().getSeries().add(seriesNameCell, chart.getType());
series.getParentSeriesGroup().setOverlap((byte)-25);
series.getParentSeriesGroup().setGapWidth(220);
series.getDataPoints().addDataPointForBarSeries(workbook.getCell(worksheetIndex, 1, 1, 4.3));
series.getDataPoints().addDataPointForBarSeries(workbook.getCell(worksheetIndex, 2, 1, 2.5));
series.getDataPoints().addDataPointForBarSeries(workbook.getCell(worksheetIndex, 3, 1, 3.5));
series.getDataPoints().addDataPointForBarSeries(workbook.getCell(worksheetIndex, 4, 1, 4.5));
return chart;
}
static void addSecondSeriesToChart(IChart chart) {
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
final int worksheetIndex = 0;
IChartDataCell seriesNameCell = workbook.getCell(worksheetIndex, 0, 2, "Series 2");
IChartSeries series = chart.getChartData().getSeries().add(seriesNameCell, ChartType.ClusteredColumn);
series.getParentSeriesGroup().setOverlap((byte)-25);
series.getParentSeriesGroup().setGapWidth(220);
series.getDataPoints().addDataPointForBarSeries(workbook.getCell(worksheetIndex, 1, 2, 2.4));
series.getDataPoints().addDataPointForBarSeries(workbook.getCell(worksheetIndex, 2, 2, 4.4));
series.getDataPoints().addDataPointForBarSeries(workbook.getCell(worksheetIndex, 3, 2, 1.8));
series.getDataPoints().addDataPointForBarSeries(workbook.getCell(worksheetIndex, 4, 2, 2.8));
}
static void addThirdSeriesToChart(IChart chart) {
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
final int worksheetIndex = 0;
IChartDataCell seriesNameCell = workbook.getCell(worksheetIndex, 0, 3, "Series 3");
IChartSeries series = chart.getChartData().getSeries().add(seriesNameCell, ChartType.Line);
series.getDataPoints().addDataPointForLineSeries(workbook.getCell(worksheetIndex, 1, 3, 2.0));
series.getDataPoints().addDataPointForLineSeries(workbook.getCell(worksheetIndex, 2, 3, 2.0));
series.getDataPoints().addDataPointForLineSeries(workbook.getCell(worksheetIndex, 3, 3, 3.0));
series.getDataPoints().addDataPointForLineSeries(workbook.getCell(worksheetIndex, 4, 3, 5.0));
series.setPlotOnSecondAxis(true);
}
static void setPrimaryAxesFormat(IChart chart) {
// Set the horizontal axis.
IAxis horizontalAxis = chart.getAxes().getHorizontalAxis();
horizontalAxis.getTextFormat().getPortionFormat().setFontHeight(12f);
horizontalAxis.getFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
setAxisTitle(horizontalAxis, "X Axis");
// Set the vertical axis.
IAxis verticalAxis = chart.getAxes().getVerticalAxis();
verticalAxis.getTextFormat().getPortionFormat().setFontHeight(12f);
verticalAxis.getFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
setAxisTitle(verticalAxis, "Y Axis 1");
// Set the vertical major gridlines color.
ILineFillFormat majorGridLinesFormat = verticalAxis.getMajorGridLinesFormat().getLine().getFillFormat();
majorGridLinesFormat.setFillType(FillType.Solid);
majorGridLinesFormat.getSolidFillColor().setColor(new Color(217, 217, 217));
}
static void setSecondaryAxesFormat(IChart chart) {
// Set the secondary horizontal axis.
IAxis secondaryHorizontalAxis = chart.getAxes().getSecondaryHorizontalAxis();
secondaryHorizontalAxis.setPosition(AxisPositionType.Bottom);
secondaryHorizontalAxis.setCrossType(CrossesType.Maximum);
secondaryHorizontalAxis.setVisible(false);
secondaryHorizontalAxis.getMajorGridLinesFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
secondaryHorizontalAxis.getMinorGridLinesFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
// Set the secondary vertical axis.
IAxis secondaryVerticalAxis = chart.getAxes().getSecondaryVerticalAxis();
secondaryVerticalAxis.setPosition(AxisPositionType.Right);
secondaryVerticalAxis.getTextFormat().getPortionFormat().setFontHeight(12f);
secondaryVerticalAxis.getFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
secondaryVerticalAxis.getMajorGridLinesFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
secondaryVerticalAxis.getMinorGridLinesFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
setAxisTitle(secondaryVerticalAxis, "Y Axis 2");
}
static void setAxisTitle(IAxis axis, String axisTitle) {
axis.setTitle(true);
axis.getTitle().setOverlay(false);
IParagraph titleParagraph = axis.getTitle().addTextFrameForOverriding(axisTitle).getParagraphs().get_Item(0);
IPortionFormat titleFormat = titleParagraph.getParagraphFormat().getDefaultPortionFormat();
titleFormat.setFontBold(NullableBool.False);
titleFormat.setFontHeight(12f);
}
Actualizar gráficos
Pasos: Actualizar gráfico de PowerPoint en Java | Pasos: Actualizar gráfico de presentación en Java | Pasos: Actualizar gráfico de presentación de PowerPoint en Java
- Instancia una clase Presentation que representa la presentación que contiene el gráfico que deseas actualizar.
- Obtén la referencia de una diapositiva usando su índice.
- Recorre todas las formas para encontrar el gráfico deseado.
- Accede a la hoja de datos del gráfico.
- Modifica los datos de la serie del gráfico cambiando los valores de la serie.
- Añade una nueva serie y completa los datos en ella.
- Guarda la presentación modificada como un archivo PPTX.
Este código Java muestra cómo actualizar un gráfico:
Presentation pres = new Presentation();
try {
// Acceder a la primera diapositiva
ISlide sld = pres.getSlides().get_Item(0);
// Obtener el gráfico con datos predeterminados
IChart chart = (IChart)sld.getShapes().get_Item(0);
// Establecer el índice de la hoja de datos del gráfico
int defaultWorksheetIndex = 0;
// Obtener la hoja de datos del gráfico
IChartDataWorkbook fact = chart.getChartData().getChartDataWorkbook();
// Cambiar el nombre de la categoría del gráfico
fact.getCell(defaultWorksheetIndex, 1, 0, "Modified Category 1");
fact.getCell(defaultWorksheetIndex, 2, 0, "Modified Category 2");
// Tomar la primera serie del gráfico
IChartSeries series = chart.getChartData().getSeries().get_Item(0);
// Ahora actualizando los datos de la serie
fact.getCell(defaultWorksheetIndex, 0, 1, "New_Series1");// Modificando el nombre de la serie
series.getDataPoints().get_Item(0).getValue().setData(90);
series.getDataPoints().get_Item(1).getValue().setData(123);
series.getDataPoints().get_Item(2).getValue().setData(44);
// Tomar la segunda serie del gráfico
series = chart.getChartData().getSeries().get_Item(1);
// Ahora actualizando los datos de la serie
fact.getCell(defaultWorksheetIndex, 0, 2, "New_Series2");// Modificando el nombre de la serie
series.getDataPoints().get_Item(0).getValue().setData(23);
series.getDataPoints().get_Item(1).getValue().setData(67);
series.getDataPoints().get_Item(2).getValue().setData(99);
// Ahora, añadiendo una nueva serie
chart.getChartData().getSeries().add(fact.getCell(defaultWorksheetIndex, 0, 3, "Series 3"), chart.getType());
// Tomar la tercera serie del gráfico
series = chart.getChartData().getSeries().get_Item(2);
// Ahora poblando los datos de la serie
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, 1, 3, 20));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, 2, 3, 50));
series.getDataPoints().addDataPointForBarSeries(fact.getCell(defaultWorksheetIndex, 3, 3, 30));
chart.setType(ChartType.ClusteredCylinder);
// Guardar la presentación con el gráfico
pres.save("AsposeChartModified_out.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Establecer rango de datos para un gráfico
Para establecer el rango de datos de un gráfico, haz lo siguiente:
- Instancia una clase Presentation que representa la presentación que contiene el gráfico.
- Obtén una referencia a una diapositiva mediante su índice.
- Recorre todas las formas para encontrar el gráfico deseado.
- Accede a los datos del gráfico y establece el rango.
- Guarda la presentación modificada como un archivo PPTX.
Este código Java muestra cómo establecer el rango de datos para un gráfico:
Presentation pres = new Presentation();
try {
ISlide slide = pres.getSlides().get_Item(0);
IChart chart = (IChart)slide.getShapes().get_Item(0);
chart.getChartData().setRange("Sheet1!A1:B4");
pres.save("SetDataRange_out.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Usar marcadores predeterminados en gráficos
Cuando usas un marcador predeterminado en gráficos, cada serie del gráfico obtiene automáticamente diferentes símbolos de marcador predeterminados.
Este código Java muestra cómo establecer automáticamente un marcador de serie de gráfico:
Presentation pres = new Presentation();
try {
ISlide slide = pres.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.LineWithMarkers, 10, 10, 400, 400);
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
IChartDataWorkbook fact = chart.getChartData().getChartDataWorkbook();
chart.getChartData().getSeries().add(fact.getCell(0, 0, 1, "Series 1"), chart.getType());
IChartSeries series = chart.getChartData().getSeries().get_Item(0);
chart.getChartData().getCategories().add(fact.getCell(0, 1, 0, "C1"));
series.getDataPoints().addDataPointForLineSeries(fact.getCell(0, 1, 1, 24));
chart.getChartData().getCategories().add(fact.getCell(0, 2, 0, "C2"));
series.getDataPoints().addDataPointForLineSeries(fact.getCell(0, 2, 1, 23));
chart.getChartData().getCategories().add(fact.getCell(0, 3, 0, "C3"));
series.getDataPoints().addDataPointForLineSeries(fact.getCell(0, 3, 1, -10));
chart.getChartData().getCategories().add(fact.getCell(0, 4, 0, "C4"));
series.getDataPoints().addDataPointForLineSeries(fact.getCell(0, 4, 1, null));
chart.getChartData().getSeries().add(fact.getCell(0, 0, 2, "Series 2"), chart.getType());
// Tomar la segunda serie del gráfico
IChartSeries series2 = chart.getChartData().getSeries().get_Item(1);
// Ahora poblando los datos de la serie
series2.getDataPoints().addDataPointForLineSeries(fact.getCell(0, 1, 2, 30));
series2.getDataPoints().addDataPointForLineSeries(fact.getCell(0, 2, 2, 10));
series2.getDataPoints().addDataPointForLineSeries(fact.getCell(0, 3, 2, 60));
series2.getDataPoints().addDataPointForLineSeries(fact.getCell(0, 4, 2, 40));
chart.setLegend(true);
chart.getLegend().setOverlay(false);
pres.save("DefaultMarkersInChart.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
FAQ
¿Qué tipos de gráficos son compatibles con Aspose.Slides?
Aspose.Slides es compatible con una amplia gama de tipos de gráficos, incluidos barras, líneas, circulares, áreas, dispersión, histogramas, radar y muchos más. Esta flexibilidad te permite elegir el tipo de gráfico más apropiado para tus necesidades de visualización de datos.
¿Cómo añado un nuevo gráfico a una diapositiva?
Para añadir un gráfico, primero creas una instancia de la clase Presentation , recuperas la diapositiva deseada usando su índice y luego llamas al método para añadir un gráfico, especificando el tipo de gráfico y los datos iniciales. Este proceso integra el gráfico directamente en tu presentación.
¿Cómo puedo actualizar los datos mostrados en un gráfico?
Puedes actualizar los datos de un gráfico accediendo a su libro de datos (IChartDataWorkbook), eliminando cualquier serie y categoría predeterminada, y luego añadiendo tus datos personalizados. Esto te permite refrescar el gráfico para reflejar los datos más recientes.
¿Es posible personalizar la apariencia del gráfico?
Sí, Aspose.Slides proporciona amplias opciones de personalización. Puedes modificar colores, fuentes, etiquetas, leyendas y otros elementos de formato para adaptar la apariencia del gráfico a tus requisitos de diseño específicos.