Crea o Aggiorna i Grafici di Presentazioni PowerPoint in Java
Panoramica
Questo articolo fornisce una guida completa su come creare e personalizzare grafici usando Aspose.Slides per Java. Imparerai come aggiungere programmaticamente un grafico a una diapositiva, popolarlo con dati e applicare varie opzioni di formattazione per soddisfare i requisiti di design specifici. Durante l’articolo, esempi di codice dettagliati illustrano ogni passaggio, dall’inizializzazione della presentazione e dell’oggetto grafico alla configurazione di serie, assi e legende. Seguendo questa guida, otterrai una solida comprensione di come integrare la generazione dinamica di grafici nelle tue applicazioni Java, semplificando il processo di creazione di presentazioni basate sui dati.
Creare un grafico
I grafici aiutano le persone a visualizzare rapidamente i dati e a ottenere intuizioni che potrebbero non essere immediatamente evidenti da una tabella o un foglio di calcolo.
Perché creare grafici?
Usando i grafici, è possibile:
- aggregare, condensare o sintetizzare grandi quantità di dati su una singola diapositiva in una presentazione;
- evidenziare pattern e tendenze nei dati;
- dedurre la direzione e lo slancio dei dati nel tempo o rispetto a un’unità di misura specifica;
- individuare outlier, aberrazioni, deviazioni, errori e dati non sensati;
- comunicare o presentare dati complessi.
In PowerPoint, è possibile creare grafici tramite la funzione Insert, che fornisce modelli per la progettazione di molti tipi di grafico. Usando Aspose.Slides, è possibile creare sia grafici regolari (basati su tipi di grafico popolari) sia grafici personalizzati.
Note
Usa l’enumerazione ChartType nel pacchetto com.aspose.slides. I valori in questa enumerazione corrispondono a diversi tipi di grafico.Creare grafici a colonne raggruppate
Questo esempio utilizza addChart per creare un grafico a colonne raggruppate che confronta due serie su tre categorie. Le serie usano riempimenti rosso e verde, e le etichette individuali mostrano i nomi delle categorie, i nomi delle serie e i valori. L’indice del foglio di lavoro 0 si riferisce al primo foglio nella cartella di lavoro incorporata del grafico.
import com.aspose.slides.*;
import java.awt.Color;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.ClusteredColumn, 20, 20, 500, 300);
chart.getChartTitle().addTextFrameForOverriding("Sample Title");
chart.getChartTitle().getTextFrameForOverriding().getTextFrameFormat().setCenterText(NullableBool.True);
chart.getChartTitle().setHeight(20);
chart.setTitle(true);
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
int worksheetIndex = 0;
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
IChartDataCell seriesNameCell = workbook.getCell(worksheetIndex, 0, 1, "Series 1");
chart.getChartData().getSeries().add(seriesNameCell, chart.getType());
seriesNameCell = workbook.getCell(worksheetIndex, 0, 2, "Series 2");
chart.getChartData().getSeries().add(seriesNameCell, chart.getType());
IChartDataCell categoryCell = workbook.getCell(worksheetIndex, 1, 0, "Category 1");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(worksheetIndex, 2, 0, "Category 2");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(worksheetIndex, 3, 0, "Category 3");
chart.getChartData().getCategories().add(categoryCell);
IChartSeries series = chart.getChartData().getSeries().get_Item(0);
IChartDataCell valueCell = workbook.getCell(worksheetIndex, 1, 1, 20);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 2, 1, 50);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 3, 1, 30);
series.getDataPoints().addDataPointForBarSeries(valueCell);
series.getFormat().getFill().setFillType(FillType.Solid);
series.getFormat().getFill().getSolidFillColor().setColor(Color.RED);
series = chart.getChartData().getSeries().get_Item(1);
valueCell = workbook.getCell(worksheetIndex, 1, 2, 30);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 2, 2, 10);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 3, 2, 60);
series.getDataPoints().addDataPointForBarSeries(valueCell);
series.getFormat().getFill().setFillType(FillType.Solid);
series.getFormat().getFill().getSolidFillColor().setColor(new Color(0, 128, 0));
IDataLabel label = series.getDataPoints().get_Item(0).getLabel();
label.getDataLabelFormat().setShowCategoryName(true);
label = series.getDataPoints().get_Item(1).getLabel();
label.getDataLabelFormat().setShowSeriesName(true);
label = series.getDataPoints().get_Item(2).getLabel();
label.getDataLabelFormat().setShowValue(true);
label.getDataLabelFormat().setShowSeriesName(true);
label.getDataLabelFormat().setSeparator("/");
presentation.save("AsposeChart.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Il risultato:

Creare grafici a dispersione
I grafici a dispersione (noti anche come scatter plot o grafici x‑y) sono spesso usati per verificare pattern o dimostrare correlazioni tra due variabili.
Usa un grafico a dispersione quando:
- Hai dati numerici in coppia.
- Hai due variabili che si associano bene.
- Vuoi determinare se le due variabili sono correlate.
- Hai una variabile indipendente che ha più valori per una variabile dipendente.
Questo esempio traccia due serie di valori x‑y. La prima serie utilizza linee rette con marcatori a stella, mentre la seconda utilizza linee fluide con marcatori a cerchio; entrambe usano una dimensione del marcatore di 10, configurata con setSize. Il metodo setSymbol controlla la forma del marcatore.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.ScatterWithSmoothLines, 20, 20, 500, 300);
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
int worksheetIndex = 0;
chart.getChartData().getSeries().clear();
IChartDataCell seriesNameCell = workbook.getCell(worksheetIndex, 1, 1, "Series 1");
chart.getChartData().getSeries().add(seriesNameCell, chart.getType());
seriesNameCell = workbook.getCell(worksheetIndex, 1, 3, "Series 2");
chart.getChartData().getSeries().add(seriesNameCell, chart.getType());
IChartSeries series = chart.getChartData().getSeries().get_Item(0);
IChartDataCell xValueCell = workbook.getCell(worksheetIndex, 2, 1, 1);
IChartDataCell yValueCell = workbook.getCell(worksheetIndex, 2, 2, 3);
series.getDataPoints().addDataPointForScatterSeries(xValueCell, yValueCell);
xValueCell = workbook.getCell(worksheetIndex, 3, 1, 2);
yValueCell = workbook.getCell(worksheetIndex, 3, 2, 10);
series.getDataPoints().addDataPointForScatterSeries(xValueCell, yValueCell);
series.setType(ChartType.ScatterWithStraightLinesAndMarkers);
series.getMarker().setSize(10);
series.getMarker().setSymbol(MarkerStyleType.Star);
series = chart.getChartData().getSeries().get_Item(1);
xValueCell = workbook.getCell(worksheetIndex, 2, 3, 5);
yValueCell = workbook.getCell(worksheetIndex, 2, 4, 2);
series.getDataPoints().addDataPointForScatterSeries(xValueCell, yValueCell);
xValueCell = workbook.getCell(worksheetIndex, 3, 3, 3);
yValueCell = workbook.getCell(worksheetIndex, 3, 4, 1);
series.getDataPoints().addDataPointForScatterSeries(xValueCell, yValueCell);
xValueCell = workbook.getCell(worksheetIndex, 4, 3, 2);
yValueCell = workbook.getCell(worksheetIndex, 4, 4, 2);
series.getDataPoints().addDataPointForScatterSeries(xValueCell, yValueCell);
xValueCell = workbook.getCell(worksheetIndex, 5, 3, 5);
yValueCell = workbook.getCell(worksheetIndex, 5, 4, 1);
series.getDataPoints().addDataPointForScatterSeries(xValueCell, yValueCell);
series.getMarker().setSize(10);
series.getMarker().setSymbol(MarkerStyleType.Circle);
presentation.save("AsposeChart.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Il risultato:

Creare grafici a torta
I grafici a torta sono ideali per mostrare la relazione parte‑intero nei dati, soprattutto quando i dati contengono etichette categoriche con valori numerici. Tuttavia, se i tuoi dati contengono molte parti o etichette, potresti considerare l’uso di un grafico a barre.
Questo esempio crea un grafico a torta con tre valori trimestrali. Ogni fetta ha un riempimento e un bordo personalizzati, e le etichette mostrano combinazioni diverse di valori, percentuali e informazioni sulla serie. Il metodo setFirstSliceAngle imposta il primo spicchio a partire da 180 gradi.
import com.aspose.slides.*;
import java.awt.Color;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.Pie, 20, 20, 500, 300);
chart.getChartTitle().addTextFrameForOverriding("Sample Title");
chart.getChartTitle().getTextFrameForOverriding().getTextFrameFormat().setCenterText(NullableBool.True);
chart.getChartTitle().setHeight(20);
chart.setTitle(true);
chart.getChartData().getSeries().get_Item(0).getLabels().getDefaultDataLabelFormat().setShowValue(true);
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
int worksheetIndex = 0;
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
IChartDataCell categoryCell = workbook.getCell(0, 1, 0, "1st Qtr");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, 2, 0, "2nd Qtr");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, 3, 0, "3rd Qtr");
chart.getChartData().getCategories().add(categoryCell);
IChartDataCell seriesNameCell = workbook.getCell(0, 0, 1, "Series 1");
IChartSeries series = chart.getChartData().getSeries().add(seriesNameCell, chart.getType());
IChartDataCell valueCell = workbook.getCell(worksheetIndex, 1, 1, 20);
series.getDataPoints().addDataPointForPieSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 2, 1, 50);
series.getDataPoints().addDataPointForPieSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 3, 1, 30);
series.getDataPoints().addDataPointForPieSeries(valueCell);
chart.getChartData().getSeriesGroups().get_Item(0).setColorVaried(true);
IChartDataPoint firstSlice = series.getDataPoints().get_Item(0);
firstSlice.getFormat().getFill().setFillType(FillType.Solid);
firstSlice.getFormat().getFill().getSolidFillColor().setColor(Color.CYAN);
firstSlice.getFormat().getLine().getFillFormat().setFillType(FillType.Solid);
firstSlice.getFormat().getLine().getFillFormat().getSolidFillColor().setColor(Color.GRAY);
firstSlice.getFormat().getLine().setWidth(3.0);
firstSlice.getFormat().getLine().setStyle(LineStyle.ThinThick);
firstSlice.getFormat().getLine().setDashStyle(LineDashStyle.LargeDash);
IChartDataPoint secondSlice = series.getDataPoints().get_Item(1);
secondSlice.getFormat().getFill().setFillType(FillType.Solid);
secondSlice.getFormat().getFill().getSolidFillColor().setColor(new Color(165, 42, 42));
secondSlice.getFormat().getLine().getFillFormat().setFillType(FillType.Solid);
secondSlice.getFormat().getLine().getFillFormat().getSolidFillColor().setColor(Color.BLUE);
secondSlice.getFormat().getLine().setWidth(3.0);
secondSlice.getFormat().getLine().setStyle(LineStyle.Single);
secondSlice.getFormat().getLine().setDashStyle(LineDashStyle.LargeDashDot);
IChartDataPoint thirdSlice = series.getDataPoints().get_Item(2);
thirdSlice.getFormat().setFillType(FillType.Solid);
thirdSlice.getFormat().getFill().getSolidFillColor().setColor(new Color(255, 127, 80));
thirdSlice.getFormat().getLine().getFillFormat().setFillType(FillType.Solid);
thirdSlice.getFormat().getLine().getFillFormat().getSolidFillColor().setColor(Color.RED);
thirdSlice.getFormat().getLine().setWidth(2.0);
thirdSlice.getFormat().getLine().setStyle(LineStyle.ThinThin);
thirdSlice.getFormat().getLine().setDashStyle(LineDashStyle.LargeDashDotDot);
IDataLabel firstLabel = series.getDataPoints().get_Item(0).getLabel();
firstLabel.getDataLabelFormat().setShowValue(true);
IDataLabel secondLabel = series.getDataPoints().get_Item(1).getLabel();
secondLabel.getDataLabelFormat().setShowValue(true);
secondLabel.getDataLabelFormat().setShowLegendKey(true);
secondLabel.getDataLabelFormat().setShowPercentage(true);
IDataLabel thirdLabel = series.getDataPoints().get_Item(2).getLabel();
thirdLabel.getDataLabelFormat().setShowSeriesName(true);
thirdLabel.getDataLabelFormat().setShowPercentage(true);
series.getLabels().getDefaultDataLabelFormat().setShowLeaderLines(true);
chart.getChartData().getSeriesGroups().get_Item(0).setFirstSliceAngle(180);
presentation.save("PieChart.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Il risultato:

Per migliorare la leggibilità delle etichette esterne alla torta, consulta Format Leader Lines per un esempio che posiziona le etichette e personalizza il colore, la larghezza, la trasparenza e lo stile tratteggiato delle linee.
Creare grafici a linee
I grafici a linee (noti anche come line graph) sono ideali quando vuoi dimostrare variazioni di valore nel tempo. Con un grafico a linee, è possibile confrontare una grande quantità di dati contemporaneamente, monitorare variazioni e tendenze nel tempo, evidenziare anomalie nelle serie di dati e altro ancora.
Questo esempio usa addChart per creare un grafico a linee con le serie e le categorie predefinite, quindi salva la presentazione come PPTX.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart lineChart = slide.getShapes().addChart(ChartType.Line, 20, 20, 500, 300);
presentation.save("lineChart.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Per impostazione predefinita, i punti su un grafico a linee sono collegati da linee continue dritte. Se desideri che i punti siano collegati da linee tratteggiate, chiama setDashStyle con un valore da LineDashStyle:
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart lineChart = slide.getShapes().addChart(ChartType.Line, 20, 20, 500, 300);
for (IChartSeries series : lineChart.getChartData().getSeries())
{
series.getFormat().getLine().setDashStyle(LineDashStyle.Dash);
}
}
finally
{
presentation.dispose();
}
Il risultato:

Creare grafici a mappa ad albero
I grafici a mappa ad albero sono ideali per dati di vendita quando vuoi mostrare la dimensione relativa delle categorie di dati e attirare rapidamente l’attenzione sugli elementi che contribuiscono maggiormente all’interno di ciascuna categoria.
Questo esempio crea una mappa ad albero con otto foglie raggruppate in quattro tronchi e due rami. Il metodo setGroupingItem assegna i tronchi al livello di raggruppamento 1 e i rami al livello 2. I valori determinano le dimensioni relative dei rettangoli, mentre le etichette di categoria e le etichette dei genitori sovrapposti identificano la gerarchia.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.Treemap, 20, 20, 500, 300);
chart.getChartData().getCategories().clear();
chart.getChartData().getSeries().clear();
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
workbook.clear(0);
// Ramo 1
IChartDataCell categoryCell = workbook.getCell(0, "C1", "Leaf1");
IChartCategory leaf = chart.getChartData().getCategories().add(categoryCell);
leaf.getGroupingLevels().setGroupingItem(1, "Stem1");
leaf.getGroupingLevels().setGroupingItem(2, "Branch1");
categoryCell = workbook.getCell(0, "C2", "Leaf2");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "C3", "Leaf3");
leaf = chart.getChartData().getCategories().add(categoryCell);
leaf.getGroupingLevels().setGroupingItem(1, "Stem2");
categoryCell = workbook.getCell(0, "C4", "Leaf4");
chart.getChartData().getCategories().add(categoryCell);
// Ramo 2
categoryCell = workbook.getCell(0, "C5", "Leaf5");
leaf = chart.getChartData().getCategories().add(categoryCell);
leaf.getGroupingLevels().setGroupingItem(1, "Stem3");
leaf.getGroupingLevels().setGroupingItem(2, "Branch2");
categoryCell = workbook.getCell(0, "C6", "Leaf6");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "C7", "Leaf7");
leaf = chart.getChartData().getCategories().add(categoryCell);
leaf.getGroupingLevels().setGroupingItem(1, "Stem4");
categoryCell = workbook.getCell(0, "C8", "Leaf8");
chart.getChartData().getCategories().add(categoryCell);
IChartSeries series = chart.getChartData().getSeries().add(ChartType.Treemap);
series.getLabels().getDefaultDataLabelFormat().setShowCategoryName(true);
IChartDataCell valueCell = workbook.getCell(0, "D1", 4);
series.getDataPoints().addDataPointForTreemapSeries(valueCell);
valueCell = workbook.getCell(0, "D2", 5);
series.getDataPoints().addDataPointForTreemapSeries(valueCell);
valueCell = workbook.getCell(0, "D3", 3);
series.getDataPoints().addDataPointForTreemapSeries(valueCell);
valueCell = workbook.getCell(0, "D4", 6);
series.getDataPoints().addDataPointForTreemapSeries(valueCell);
valueCell = workbook.getCell(0, "D5", 9);
series.getDataPoints().addDataPointForTreemapSeries(valueCell);
valueCell = workbook.getCell(0, "D6", 9);
series.getDataPoints().addDataPointForTreemapSeries(valueCell);
valueCell = workbook.getCell(0, "D7", 4);
series.getDataPoints().addDataPointForTreemapSeries(valueCell);
valueCell = workbook.getCell(0, "D8", 3);
series.getDataPoints().addDataPointForTreemapSeries(valueCell);
series.setParentLabelLayout(ParentLabelLayoutType.Overlapping);
presentation.save("Treemap.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Il risultato:

Creare grafici a cascata
Un grafico a cascata mostra come le variazioni positive e negative contribuiscono a un valore finale. Ad esempio, una scomposizione del profitto può iniziare con i ricavi, sottrarre i costi e aggiungere altri introiti. Le colonne di variazione fluttuano tra i valori correnti precedenti e quelli nuovi, mentre le colonne totali si estendono dallo zero al valore accumulato.
L’esempio seguente utilizza importi in migliaia di dollari USA:
| Categoria | Valore del workbook | Tipo di colonna |
|---|---|---|
| Revenue | 1000 | Increase |
| Cost of sales | -400 | Decrease |
| Gross profit | 600 | Intermediate total |
| Operating expenses | -200 | Decrease |
| Other income | 50 | Increase |
| Net profit | 450 | Final total |
Per contrassegnare un punto come totale intermedio o finale, chiama il suo metodo setSetAsTotal con true. Fornisci l’importo accumulato effettivo nella cella del foglio di lavoro per quel punto: 600 per il profitto lordo (1000 - 400) e 450 per il profitto netto (600 - 200 + 50). Il metodo segna la colonna come totale; non calcola né popola il valore della cella. Non utilizzare zero come segnaposto né fornire un’altra variazione per un punto totale. Una colonna totale visualizza il valore accumulato senza aggiungerlo nuovamente al valore corrente.
Questo esempio Java completo crea un grafico usando il membro Waterfall di ChartType, cancella i dati predefiniti e popola la cartella di lavoro incorporata. L’indice del foglio di lavoro 0 seleziona il primo foglio; la colonna A contiene i nomi delle categorie e la colonna B i valori. Ogni cella valore viene aggiunta con addDataPointForWaterfallSeries. Gli indici dei punti basati su zero 2 e 5 identificano rispettivamente i totali intermedi e finali. Chiamando setShowValue con true si visualizzano gli importi sulle colonne. Non è necessaria alcuna presentazione o cartella di lavoro di input.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.Waterfall, 20, 20, 680, 200);
chart.setTitle(true);
chart.getChartTitle().addTextFrameForOverriding("Profit breakdown (USD thousands)");
chart.getChartTitle().setOverlay(false);
chart.setLegend(false);
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
int worksheetIndex = 0;
workbook.clear(worksheetIndex);
IChartDataCell seriesNameCell = workbook.getCell(worksheetIndex, 0, 1, "Profit");
IChartSeries series = chart.getChartData().getSeries().add(seriesNameCell, ChartType.Waterfall);
String[] categories = new String[] { "Revenue", "Cost of sales", "Gross profit", "Operating expenses", "Other income", "Net profit" };
double[] values = new double[] { 1000, -400, 600, -200, 50, 450 };
for (int i = 0; i < categories.length; i++)
{
IChartDataCell categoryCell = workbook.getCell(worksheetIndex, i + 1, 0, categories[i]);
chart.getChartData().getCategories().add(categoryCell);
IChartDataCell valueCell = workbook.getCell(worksheetIndex, i + 1, 1, values[i]);
series.getDataPoints().addDataPointForWaterfallSeries(valueCell);
}
// Il terzo e il sesto punto rappresentano totali, non cambiamenti aggiuntivi.
series.getDataPoints().get_Item(2).setSetAsTotal(true);
series.getDataPoints().get_Item(5).setSetAsTotal(true);
series.setShowConnectorLines(true);
series.getLabels().getDefaultDataLabelFormat().setShowValue(true);
presentation.save("WaterfallChart.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Chiama il metodo a livello di serie setShowConnectorLines con true per mostrare le linee che collegano colonne consecutive e rendere più chiaro il valore corrente. Per nascondere queste linee, sostituisci la chiamata al metodo nell’esempio con series.setShowConnectorLines(false); prima di salvare. Questa modifica influisce solo sulla visibilità delle linee, non sui dati o sui totali.
La presentazione salvata mostra un profitto lordo di 600 e un profitto netto di 450, entrambi i totali calcolati da zero:

Creare grafici a candela (Stock)
I grafici a candela sono usati per visualizzare dati finanziari come prezzi di apertura, massimo, minimo e chiusura, aiutando a analizzare tendenze di mercato e volatilità. Offrono informazioni essenziali sulle prestazioni di un titolo, supportando investitori e analisti nelle decisioni informate.
Questo esempio crea un grafico open‑high‑low‑close con quattro serie in quest’ordine e tre categorie. Il metodo setUpDownBars abilita le barre up/down, e getHiLowLinesFormat controlla le linee high‑low che mostrano gli intervalli di prezzo, mentre le linee delle singole serie e le linee di griglia orizzontali minori sono nascoste.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.OpenHighLowClose, 20, 20, 500, 300, false);
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
IChartDataCell categoryCell = workbook.getCell(0, 1, 0, "A");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, 2, 0, "B");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, 3, 0, "C");
chart.getChartData().getCategories().add(categoryCell);
IChartDataCell seriesNameCell = workbook.getCell(0, 0, 1, "Open");
chart.getChartData().getSeries().add(seriesNameCell, ChartType.OpenHighLowClose);
seriesNameCell = workbook.getCell(0, 0, 2, "High");
chart.getChartData().getSeries().add(seriesNameCell, ChartType.OpenHighLowClose);
seriesNameCell = workbook.getCell(0, 0, 3, "Low");
chart.getChartData().getSeries().add(seriesNameCell, ChartType.OpenHighLowClose);
seriesNameCell = workbook.getCell(0, 0, 4, "Close");
chart.getChartData().getSeries().add(seriesNameCell, ChartType.OpenHighLowClose);
IChartSeries series = chart.getChartData().getSeries().get_Item(0);
IChartDataCell valueCell = workbook.getCell(0, 1, 1, 72);
series.getDataPoints().addDataPointForStockSeries(valueCell);
valueCell = workbook.getCell(0, 2, 1, 25);
series.getDataPoints().addDataPointForStockSeries(valueCell);
valueCell = workbook.getCell(0, 3, 1, 38);
series.getDataPoints().addDataPointForStockSeries(valueCell);
series = chart.getChartData().getSeries().get_Item(1);
valueCell = workbook.getCell(0, 1, 2, 172);
series.getDataPoints().addDataPointForStockSeries(valueCell);
valueCell = workbook.getCell(0, 2, 2, 57);
series.getDataPoints().addDataPointForStockSeries(valueCell);
valueCell = workbook.getCell(0, 3, 2, 57);
series.getDataPoints().addDataPointForStockSeries(valueCell);
series = chart.getChartData().getSeries().get_Item(2);
valueCell = workbook.getCell(0, 1, 3, 12);
series.getDataPoints().addDataPointForStockSeries(valueCell);
valueCell = workbook.getCell(0, 2, 3, 12);
series.getDataPoints().addDataPointForStockSeries(valueCell);
valueCell = workbook.getCell(0, 3, 3, 13);
series.getDataPoints().addDataPointForStockSeries(valueCell);
series = chart.getChartData().getSeries().get_Item(3);
valueCell = workbook.getCell(0, 1, 4, 25);
series.getDataPoints().addDataPointForStockSeries(valueCell);
valueCell = workbook.getCell(0, 2, 4, 38);
series.getDataPoints().addDataPointForStockSeries(valueCell);
valueCell = workbook.getCell(0, 3, 4, 50);
series.getDataPoints().addDataPointForStockSeries(valueCell);
chart.getChartData().getSeriesGroups().get_Item(0).getUpDownBars().setUpDownBars(true);
chart.getChartData().getSeriesGroups().get_Item(0).getHiLowLinesFormat().getLine().getFillFormat().setFillType(FillType.Solid);
for (IChartSeries stockSeries : chart.getChartData().getSeries())
{
stockSeries.getFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
}
chart.getAxes().getVerticalAxis().getMinorGridLinesFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
presentation.save("Stock-chart.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Il risultato:

Creare grafici a scatola e baffi
I grafici a scatola e baffi mostrano la distribuzione dei dati riassumendo misure statistiche chiave, come la mediana, i quartili e gli eventuali outlier. Sono particolarmente utili in analisi esplorative dei dati e studi statistici per comprendere rapidamente la variabilità dei dati e identificare anomalie.
Questo esempio crea un grafico a scatola e baffi a partire da sei valori. Il metodo setQuartileMethod seleziona il calcolo dei quartili esclusivo. L’esempio abilita anche le linee della media, i marcatori della media, i punti interni e i punti outlier.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.BoxAndWhisker, 20, 20, 500, 300);
chart.getChartData().getCategories().clear();
chart.getChartData().getSeries().clear();
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
workbook.clear(0);
IChartDataCell categoryCell = workbook.getCell(0, "A1", "Category 1");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "A2", "Category 2");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "A3", "Category 3");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "A4", "Category 4");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "A5", "Category 5");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "A6", "Category 6");
chart.getChartData().getCategories().add(categoryCell);
IChartSeries series = chart.getChartData().getSeries().add(ChartType.BoxAndWhisker);
series.setQuartileMethod(QuartileMethodType.Exclusive);
series.setShowMeanLine(true);
series.setShowMeanMarkers(true);
series.setShowInnerPoints(true);
series.setShowOutlierPoints(true);
IChartDataCell valueCell = workbook.getCell(0, "B1", 15);
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(valueCell);
valueCell = workbook.getCell(0, "B2", 41);
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(valueCell);
valueCell = workbook.getCell(0, "B3", 16);
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(valueCell);
valueCell = workbook.getCell(0, "B4", 10);
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(valueCell);
valueCell = workbook.getCell(0, "B5", 23);
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(valueCell);
valueCell = workbook.getCell(0, "B6", 16);
series.getDataPoints().addDataPointForBoxAndWhiskerSeries(valueCell);
presentation.save("BoxAndWhisker.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Creare grafici a imbuto
I grafici a imbuto visualizzano processi che coinvolgono fasi sequenziali, dove il volume dei dati diminuisce man mano che avanza da un passaggio al successivo. Sono particolarmente utili per analizzare i tassi di conversione, identificare colli di bottiglia e monitorare l’efficienza dei processi di vendita o marketing.
Questo esempio usa addChart per aggiungere un grafico a imbuto alla prima diapositiva di una presentazione esistente. Sostituisce i dati predefiniti con sei categorie e valori compresi tra 50 e 500, quindi salva la presentazione aggiornata. La presentazione di input deve contenere almeno una diapositiva.
import com.aspose.slides.*;
Presentation presentation = new Presentation("test.pptx");
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.Funnel, 50, 50, 500, 400);
chart.getChartData().getCategories().clear();
chart.getChartData().getSeries().clear();
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
workbook.clear(0);
IChartDataCell categoryCell = workbook.getCell(0, "A1", "Category 1");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "A2", "Category 2");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "A3", "Category 3");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "A4", "Category 4");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "A5", "Category 5");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "A6", "Category 6");
chart.getChartData().getCategories().add(categoryCell);
IChartSeries series = chart.getChartData().getSeries().add(ChartType.Funnel);
IChartDataCell valueCell = workbook.getCell(0, "B1", 50);
series.getDataPoints().addDataPointForFunnelSeries(valueCell);
valueCell = workbook.getCell(0, "B2", 100);
series.getDataPoints().addDataPointForFunnelSeries(valueCell);
valueCell = workbook.getCell(0, "B3", 200);
series.getDataPoints().addDataPointForFunnelSeries(valueCell);
valueCell = workbook.getCell(0, "B4", 300);
series.getDataPoints().addDataPointForFunnelSeries(valueCell);
valueCell = workbook.getCell(0, "B5", 400);
series.getDataPoints().addDataPointForFunnelSeries(valueCell);
valueCell = workbook.getCell(0, "B6", 500);
series.getDataPoints().addDataPointForFunnelSeries(valueCell);
presentation.save("Funnel.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Il risultato:

Creare grafici a esplosione (Sunburst)
I grafici a esplosione sono usati per visualizzare dati gerarchici, mostrando i livelli come anelli concentrici. Aiutano a illustrare relazioni parte‑intero e sono ideali per rappresentare categorie e sotto‑categorie nidificate in modo chiaro e compatto.
Questo esempio crea un grafico a esplosione con otto foglie raggruppate in quattro tronchi e due rami. Il metodo setGroupingItem assegna i tronchi al livello di raggruppamento 1 e i rami al livello 2. Le etichette di categoria identificano i segmenti e i valori determinano le loro dimensioni relative.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.Sunburst, 20, 20, 500, 300);
chart.getChartData().getCategories().clear();
chart.getChartData().getSeries().clear();
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
workbook.clear(0);
// Ramo 1
IChartDataCell categoryCell = workbook.getCell(0, "C1", "Leaf1");
IChartCategory leaf = chart.getChartData().getCategories().add(categoryCell);
leaf.getGroupingLevels().setGroupingItem(1, "Stem1");
leaf.getGroupingLevels().setGroupingItem(2, "Branch1");
categoryCell = workbook.getCell(0, "C2", "Leaf2");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "C3", "Leaf3");
leaf = chart.getChartData().getCategories().add(categoryCell);
leaf.getGroupingLevels().setGroupingItem(1, "Stem2");
categoryCell = workbook.getCell(0, "C4", "Leaf4");
chart.getChartData().getCategories().add(categoryCell);
// Ramo 2
categoryCell = workbook.getCell(0, "C5", "Leaf5");
leaf = chart.getChartData().getCategories().add(categoryCell);
leaf.getGroupingLevels().setGroupingItem(1, "Stem3");
leaf.getGroupingLevels().setGroupingItem(2, "Branch2");
categoryCell = workbook.getCell(0, "C6", "Leaf6");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "C7", "Leaf7");
leaf = chart.getChartData().getCategories().add(categoryCell);
leaf.getGroupingLevels().setGroupingItem(1, "Stem4");
categoryCell = workbook.getCell(0, "C8", "Leaf8");
chart.getChartData().getCategories().add(categoryCell);
IChartSeries series = chart.getChartData().getSeries().add(ChartType.Sunburst);
series.getLabels().getDefaultDataLabelFormat().setShowCategoryName(true);
IChartDataCell valueCell = workbook.getCell(0, "D1", 4);
series.getDataPoints().addDataPointForSunburstSeries(valueCell);
valueCell = workbook.getCell(0, "D2", 5);
series.getDataPoints().addDataPointForSunburstSeries(valueCell);
valueCell = workbook.getCell(0, "D3", 3);
series.getDataPoints().addDataPointForSunburstSeries(valueCell);
valueCell = workbook.getCell(0, "D4", 6);
series.getDataPoints().addDataPointForSunburstSeries(valueCell);
valueCell = workbook.getCell(0, "D5", 9);
series.getDataPoints().addDataPointForSunburstSeries(valueCell);
valueCell = workbook.getCell(0, "D6", 9);
series.getDataPoints().addDataPointForSunburstSeries(valueCell);
valueCell = workbook.getCell(0, "D7", 4);
series.getDataPoints().addDataPointForSunburstSeries(valueCell);
valueCell = workbook.getCell(0, "D8", 3);
series.getDataPoints().addDataPointForSunburstSeries(valueCell);
presentation.save("Sunburst.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Il risultato:

Creare grafici istogramma
Gli istogrammi mostrano come i valori numerici sono distribuiti su intervalli (bin). Per report mensili sui tempi di elaborazione degli ordini, usa la stessa larghezza del bin e le stesse soglie per mantenere gli intervalli coerenti e facilitare il confronto delle distribuzioni.
Chiama setAggregationType sull’asse orizzontale con una modalità da AxisAggregationType. setBinWidth si applica solo a ByBinWidth; setNumberOfBins si applica solo a ByNumberOfBins. Usa Automatic per lasciare che il grafico scelga i bin.
Usare una larghezza fissa del bin
Questo esempio raggruppa i tempi di elaborazione in intervalli di 10 minuti, con bin separati per i tempi ≤ 10 minuti e > 40 minuti. Abilita questi bin con setUnderflowBin e setOverflowBin. Quando si forniscono soglie esplicite tramite setUnderflowBin e setOverflowBin, chiama setAutomaticUnderflowBin e setAutomaticOverflowBin con false.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.Histogram, 20, 20, 680, 200);
chart.setLegend(false);
chart.setTitle(false);
chart.getChartData().getCategories().clear();
chart.getChartData().getSeries().clear();
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
workbook.clear(0);
IChartSeries series = chart.getChartData().getSeries().add(ChartType.Histogram);
double[] values = { 5, 10, 10, 11, 15, 20, 20, 21, 25, 30, 30, 31, 35, 40, 40, 41, 50 };
for (int i = 0; i < values.length; i++)
{
IChartDataCell valueCell = workbook.getCell(0, i, 0, values[i]);
series.getDataPoints().addDataPointForHistogramSeries(valueCell);
}
IAxis axis = chart.getAxes().getHorizontalAxis();
axis.setAggregationType(AxisAggregationType.ByBinWidth);
axis.setBinWidth(10);
axis.setUnderflowBin(true);
axis.setAutomaticUnderflowBin(false);
axis.setUnderflowBin(10);
axis.setOverflowBin(true);
axis.setAutomaticOverflowBin(false);
axis.setOverflowBin(40);
presentation.save("Histogram-bin-width.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
La presentazione mostrata in PowerPoint indica conteggi dei bin di 3, 4, 4, 4 e 2. Il bin di underflow include 5, 10, 10, quindi la sua soglia è inclusiva. Il bin di overflow include solo 41, 50, quindi la sua soglia è esclusiva; entrambi i valori uguali a 40 rimangono nell’intervallo precedente. I bin interni contengono valori maggiori del loro limite inferiore e minori o uguali al loro limite superiore.

Specificare il numero di bin
Per un livello di dettaglio fisso invece di intervalli fissi, richiedi cinque bin per gli stessi dati. Questo esempio lascia i bin di underflow e overflow disabilitati. Il grafico determina la larghezza dai dati, quindi i limiti possono variare tra i report.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.Histogram, 20, 20, 680, 200);
chart.setLegend(false);
chart.setTitle(false);
chart.getChartData().getCategories().clear();
chart.getChartData().getSeries().clear();
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
workbook.clear(0);
IChartSeries series = chart.getChartData().getSeries().add(ChartType.Histogram);
double[] values = { 5, 10, 10, 11, 15, 20, 20, 21, 25, 30, 30, 31, 35, 40, 40, 41, 50 };
for (int i = 0; i < values.length; i++)
{
IChartDataCell valueCell = workbook.getCell(0, i, 0, values[i]);
series.getDataPoints().addDataPointForHistogramSeries(valueCell);
}
IAxis axis = chart.getAxes().getHorizontalAxis();
axis.setAggregationType(AxisAggregationType.ByNumberOfBins);
axis.setNumberOfBins(5);
presentation.save("Histogram-bin-count.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
I cinque bin hanno conteggi di 4, 4, 4, 4 e 1. Confronta questa distribuzione con il risultato a larghezza fissa sopra: i valori di input sono identici, ma i limiti differiscono.

Creare grafici radar
I grafici radar visualizzano dati multivariati in un formato bidimensionale, permettendo un facile confronto di più variabili simultaneamente. Sono particolarmente utili per identificare pattern, punti di forza e debolezze su più metriche o attributi di prestazione.
Questo esempio usa addChart per creare un grafico radar con le serie e le categorie predefinite, quindi salva la presentazione come PPTX.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
slide.getShapes().addChart(ChartType.Radar, 20, 20, 500, 300);
presentation.save("Radar-chart.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Il risultato:

Creare grafici a più categorie
I grafici a più categorie mostrano dati che coinvolgono più raggruppamenti categorici, permettendo di confrontare valori su più dimensioni simultaneamente. Sono particolarmente utili quando è necessario analizzare tendenze e relazioni in set di dati complessi e multilivello.
Questo esempio crea un grafico a colonne raggruppate con otto categorie disposte in quattro coppie. Il metodo setGroupingItem assegna a ogni coppia un’etichetta condivisa al livello di raggruppamento 1, producendo un asse delle categorie con etichette sia individuali sia di gruppo.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.ClusteredColumn, 20, 20, 500, 300);
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
workbook.clear(0);
int worksheetIndex = 0;
IChartDataCell categoryCell = workbook.getCell(0, "c2", "A");
IChartCategory category = chart.getChartData().getCategories().add(categoryCell);
category.getGroupingLevels().setGroupingItem(1, "Group1");
categoryCell = workbook.getCell(0, "c3", "B");
category = chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "c4", "C");
category = chart.getChartData().getCategories().add(categoryCell);
category.getGroupingLevels().setGroupingItem(1, "Group2");
categoryCell = workbook.getCell(0, "c5", "D");
category = chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "c6", "E");
category = chart.getChartData().getCategories().add(categoryCell);
category.getGroupingLevels().setGroupingItem(1, "Group3");
categoryCell = workbook.getCell(0, "c7", "F");
category = chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(0, "c8", "G");
category = chart.getChartData().getCategories().add(categoryCell);
category.getGroupingLevels().setGroupingItem(1, "Group4");
categoryCell = workbook.getCell(0, "c9", "H");
category = chart.getChartData().getCategories().add(categoryCell);
IChartDataCell seriesNameCell = workbook.getCell(0, "D1", "Series 1");
IChartSeries series = chart.getChartData().getSeries().add(seriesNameCell, ChartType.ClusteredColumn);
IChartDataCell valueCell = workbook.getCell(worksheetIndex, "D2", 10);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, "D3", 20);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, "D4", 30);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, "D5", 40);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, "D6", 50);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, "D7", 60);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, "D8", 70);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, "D9", 80);
series.getDataPoints().addDataPointForBarSeries(valueCell);
presentation.save("AsposeChart.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Il risultato:

Creare grafici cartografici
I grafici cartografici visualizzano dati geografici mappando informazioni a posizioni specifiche come paesi, stati o città. Sono particolarmente utili per analizzare tendenze regionali, dati demografici e distribuzioni spaziali in modo chiaro e visivamente coinvolgente.
Questo esempio usa addChart per creare un grafico cartografico con i dati geografici predefiniti e lo salva per la visualizzazione in PowerPoint.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.Map, 20, 20, 500, 300);
presentation.save("mapChart.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Il risultato:

Note
L’immagine sopra mostra la presentazione salvata aperta in PowerPoint. Aspose.Slides scrive correttamente il grafico cartografico e i suoi dati, ma non disegna i grafici cartografici da sé: quando una diapositiva che ne contiene è renderizzata in un’immagine o convertita in PDF o SVG, l’area del grafico risulta vuota. Le altre forme sulla stessa diapositiva non sono influenzate.Creare grafici combinati
Un grafico combinato (o combo) combina due o più tipi di grafico in un unico grafico. Questo grafico consente di evidenziare, confrontare o esaminare differenze tra due o più set di dati, aiutando a identificare le relazioni tra di essi.

Questo esempio combina due serie a colonne raggruppate con una serie a linee su quattro categorie. Le colonne usano l’asse verticale primario, mentre setPlotOnSecondAxis posiziona la linea su un asse verticale secondario a destra. Le funzioni di supporto configurano titolo, leggenda, etichette degli assi e linee di griglia.
import com.aspose.slides.*;
import java.awt.Color;
class ComboChartExample
{
void createComboChart()
{
Presentation presentation = new Presentation();
try
{
IChart chart = createChartWithFirstSeries(presentation.getSlides().get_Item(0));
addSecondSeriesToChart(chart);
addThirdSeriesToChart(chart);
setPrimaryAxesFormat(chart);
setSecondaryAxesFormat(chart);
presentation.save("combo-chart.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
}
IChart createChartWithFirstSeries(ISlide slide)
{
IChart chart = slide.getShapes().addChart(ChartType.ClusteredColumn, 50, 50, 600, 400);
chart.setTitle(true);
chart.getChartTitle().addTextFrameForOverriding("Chart Title");
chart.getChartTitle().setOverlay(false);
IPortionFormat portionFormat = chart.getChartTitle().getTextFrameForOverriding().getParagraphs().get_Item(0).getParagraphFormat().getDefaultPortionFormat();
portionFormat.setFontBold(NullableBool.False);
portionFormat.setFontHeight(18f);
chart.getLegend().setPosition(LegendPositionType.Bottom);
chart.getLegend().getTextFormat().getPortionFormat().setFontHeight(12f);
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
int worksheetIndex = 0;
IChartDataCell categoryCell = workbook.getCell(worksheetIndex, 1, 0, "Category 1");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(worksheetIndex, 2, 0, "Category 2");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(worksheetIndex, 3, 0, "Category 3");
chart.getChartData().getCategories().add(categoryCell);
categoryCell = workbook.getCell(worksheetIndex, 4, 0, "Category 4");
chart.getChartData().getCategories().add(categoryCell);
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);
IChartDataCell valueCell = workbook.getCell(worksheetIndex, 1, 1, 4.3);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 2, 1, 2.5);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 3, 1, 3.5);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 4, 1, 4.5);
series.getDataPoints().addDataPointForBarSeries(valueCell);
return chart;
}
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);
IChartDataCell valueCell = workbook.getCell(worksheetIndex, 1, 2, 2.4);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 2, 2, 4.4);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 3, 2, 1.8);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 4, 2, 2.8);
series.getDataPoints().addDataPointForBarSeries(valueCell);
}
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);
IChartDataCell valueCell = workbook.getCell(worksheetIndex, 1, 3, 2.0);
series.getDataPoints().addDataPointForLineSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 2, 3, 2.0);
series.getDataPoints().addDataPointForLineSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 3, 3, 3.0);
series.getDataPoints().addDataPointForLineSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 4, 3, 5.0);
series.getDataPoints().addDataPointForLineSeries(valueCell);
series.setPlotOnSecondAxis(true);
}
void setPrimaryAxesFormat(IChart chart)
{
IAxis horizontalAxis = chart.getAxes().getHorizontalAxis();
horizontalAxis.getTextFormat().getPortionFormat().setFontHeight(12f);
horizontalAxis.getFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
setAxisTitle(horizontalAxis, "X Axis");
IAxis verticalAxis = chart.getAxes().getVerticalAxis();
verticalAxis.getTextFormat().getPortionFormat().setFontHeight(12f);
verticalAxis.getFormat().getLine().getFillFormat().setFillType(FillType.NoFill);
setAxisTitle(verticalAxis, "Y Axis 1");
ILineFillFormat majorGridLinesFormat = verticalAxis.getMajorGridLinesFormat().getLine().getFillFormat();
majorGridLinesFormat.setFillType(FillType.Solid);
majorGridLinesFormat.getSolidFillColor().setColor(new Color(217, 217, 217));
}
void setSecondaryAxesFormat(IChart chart)
{
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);
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");
}
void setAxisTitle(IAxis axis, String axisTitle)
{
axis.setTitle(true);
axis.getTitle().setOverlay(false);
IPortionFormat titlePortionFormat = axis.getTitle().addTextFrameForOverriding(axisTitle).getParagraphs().get_Item(0).getParagraphFormat().getDefaultPortionFormat();
titlePortionFormat.setFontBold(NullableBool.False);
titlePortionFormat.setFontHeight(12f);
}
}
ComboChartExample example = new ComboChartExample();
example.createComboChart();
Aggiornare i grafici
Aspose.Slides per Java consente di aggiornare i grafici PowerPoint modificando dati, formattazione e stile del grafico. Questa funzionalità semplifica il processo di mantenimento delle presentazioni aggiornate con contenuti dinamici e garantisce che i grafici riflettano accuratamente i dati e gli standard visivi correnti.
Questo esempio aggiorna il grafico denominato “My chart” sulla prima diapositiva di una presentazione esistente. Richiede due serie di colonna con tre punti dati ciascuna, con etichette di categoria nella colonna A e nomi di serie nella prima riga del primo foglio di lavoro. L’esempio utilizza getCell per modificare le celle del workbook, aggiorna i valori delle serie, aggiunge una terza serie e cambia il grafico in cilindri raggruppati tramite setType.
import com.aspose.slides.*;
final String chartName = "My chart";
Presentation presentation = new Presentation("ExistingChart.pptx");
try
{
ISlide slide = presentation.getSlides().get_Item(0);
for (IShape shape : slide.getShapes())
{
if (shape instanceof IChart && chartName.equals(shape.getName()))
{
IChart chart = (IChart) shape;
int worksheetIndex = 0;
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
workbook.getCell(worksheetIndex, 1, 0, "Modified Category 1");
workbook.getCell(worksheetIndex, 2, 0, "Modified Category 2");
IChartSeries series = chart.getChartData().getSeries().get_Item(0);
workbook.getCell(worksheetIndex, 0, 1, "New_Series 1");
series.getDataPoints().get_Item(0).getValue().setData(90);
series.getDataPoints().get_Item(1).getValue().setData(123);
series.getDataPoints().get_Item(2).getValue().setData(44);
series = chart.getChartData().getSeries().get_Item(1);
workbook.getCell(worksheetIndex, 0, 2, "New_Series 2");
series.getDataPoints().get_Item(0).getValue().setData(23);
series.getDataPoints().get_Item(1).getValue().setData(67);
series.getDataPoints().get_Item(2).getValue().setData(99);
IChartDataCell seriesNameCell = workbook.getCell(worksheetIndex, 0, 3, "Series 3");
series = chart.getChartData().getSeries().add(seriesNameCell, chart.getType());
IChartDataCell valueCell = workbook.getCell(worksheetIndex, 1, 3, 20);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 2, 3, 50);
series.getDataPoints().addDataPointForBarSeries(valueCell);
valueCell = workbook.getCell(worksheetIndex, 3, 3, 30);
series.getDataPoints().addDataPointForBarSeries(valueCell);
chart.setType(ChartType.ClusteredCylinder);
}
}
presentation.save("AsposeChartModified.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Impostare l’intervallo dati per un grafico
Per ispezionare l’intervallo già utilizzato da un grafico esistente, consulta Retrieve a Chart’s Data Range.
Aspose.Slides per Java offre la flessibilità di definire un intervallo dati specifico da un foglio di lavoro come sorgente per i dati del tuo grafico. Ciò significa che puoi mappare direttamente una parte del foglio di lavoro al grafico, controllando quali celle contribuiscono a serie e categorie. Di conseguenza, puoi aggiornare e sincronizzare facilmente i grafici con le ultime modifiche dei dati nel foglio di lavoro, assicurando che le tue presentazioni PowerPoint riflettano informazioni attuali e accurate.
Questo esempio usa setRange per impostare la sorgente dati del grafico denominato “My chart” sulla prima diapositiva di una presentazione esistente a Sheet1!A1:B4. Il workbook del grafico deve contenere quel foglio di lavoro e un intervallo popolato con un’intestazione di serie nella prima riga, etichette di categoria nella colonna A e tre valori nella colonna B.
import com.aspose.slides.*;
final String chartName = "My chart";
Presentation presentation = new Presentation("ExistingChart.pptx");
try
{
ISlide slide = presentation.getSlides().get_Item(0);
for (IShape shape : slide.getShapes())
{
if (shape instanceof IChart && chartName.equals(shape.getName()))
{
IChart chart = (IChart) shape;
chart.getChartData().setRange("Sheet1!A1:B4");
}
}
presentation.save("SetDataRange.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
Usare marcatori predefiniti nei grafici
Quando usi marcatori predefiniti nei grafici, ciascuna serie del grafico ottiene automaticamente un simbolo di marcatore predefinito diverso.
Questo esempio usa addChart per creare un grafico con due serie a linee e una leggenda. Le impostazioni del marcatore accessibili tramite getMarker mantengono i simboli di marcatore assegnati automaticamente. La prima serie include un valore negativo e un valore mancante, rappresentato da null, mentre la seconda ha un valore per ogni categoria.
import com.aspose.slides.*;
Presentation presentation = new Presentation();
try
{
ISlide slide = presentation.getSlides().get_Item(0);
IChart chart = slide.getShapes().addChart(ChartType.LineWithMarkers, 10, 10, 400, 400);
chart.getChartData().getSeries().clear();
chart.getChartData().getCategories().clear();
IChartDataWorkbook workbook = chart.getChartData().getChartDataWorkbook();
IChartDataCell seriesNameCell = workbook.getCell(0, 0, 1, "Series 1");
IChartSeries series = chart.getChartData().getSeries().add(seriesNameCell, chart.getType());
IChartDataCell categoryCell = workbook.getCell(0, 1, 0, "C1");
chart.getChartData().getCategories().add(categoryCell);
IChartDataCell valueCell = workbook.getCell(0, 1, 1, 24);
series.getDataPoints().addDataPointForLineSeries(valueCell);
categoryCell = workbook.getCell(0, 2, 0, "C2");
chart.getChartData().getCategories().add(categoryCell);
valueCell = workbook.getCell(0, 2, 1, 23);
series.getDataPoints().addDataPointForLineSeries(valueCell);
categoryCell = workbook.getCell(0, 3, 0, "C3");
chart.getChartData().getCategories().add(categoryCell);
valueCell = workbook.getCell(0, 3, 1, -10);
series.getDataPoints().addDataPointForLineSeries(valueCell);
categoryCell = workbook.getCell(0, 4, 0, "C4");
chart.getChartData().getCategories().add(categoryCell);
valueCell = workbook.getCell(0, 4, 1, null);
series.getDataPoints().addDataPointForLineSeries(valueCell);
seriesNameCell = workbook.getCell(0, 0, 2, "Series 2");
IChartSeries secondSeries = chart.getChartData().getSeries().add(seriesNameCell, chart.getType());
valueCell = workbook.getCell(0, 1, 2, 30);
secondSeries.getDataPoints().addDataPointForLineSeries(valueCell);
valueCell = workbook.getCell(0, 2, 2, 10);
secondSeries.getDataPoints().addDataPointForLineSeries(valueCell);
valueCell = workbook.getCell(0, 3, 2, 60);
secondSeries.getDataPoints().addDataPointForLineSeries(valueCell);
valueCell = workbook.getCell(0, 4, 2, 40);
secondSeries.getDataPoints().addDataPointForLineSeries(valueCell);
chart.setLegend(true);
chart.getLegend().setOverlay(false);
presentation.save("DefaultMarkersInChart.pptx", SaveFormat.Pptx);
}
finally
{
presentation.dispose();
}
FAQ
Quali tipi di grafico sono supportati da Aspose.Slides per Java?
Aspose.Slides per Java supporta un’ampia gamma di tipi di grafico, tra cui barre, linee, torta, area, dispersione, istogramma, radar e molti altri. Questa flessibilità consente di scegliere il tipo di grafico più appropriato per le esigenze di visualizzazione dei dati.
Come aggiungo un nuovo grafico a una diapositiva?
Per aggiungere un grafico, crei prima un’istanza della classe Presentation, recuperi la diapositiva desiderata usando il suo indice, quindi chiami il metodo per aggiungere un grafico, specificando il tipo di grafico e i dati iniziali. Questo processo integra il grafico direttamente nella tua presentazione.
Come posso aggiornare i dati visualizzati in un grafico?
Puoi aggiornare i dati di un grafico accedendo al suo workbook dati (IChartDataWorkbook), cancellando eventuali serie e categorie predefinite, e quindi aggiungendo i tuoi dati personalizzati. Questo ti consente di rinfrescare programmaticamente il grafico per riflettere gli ultimi dati.
È possibile personalizzare l’aspetto del grafico?
Sì, Aspose.Slides per Java offre ampie opzioni di personalizzazione. Puoi modificare colori, caratteri, etichette, leggende e altri elementi di formattazione per adattare l’aspetto del grafico ai requisiti di design specifici.