Crea o aggiorna grafici per presentazioni PowerPoint in Java
Panoramica
Questo articolo fornisce una guida completa su come creare e personalizzare i grafici utilizzando 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.
Crea 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 da un foglio di calcolo.
Perché creare grafici?
Utilizzando i grafici, è possibile:
- aggregare, condensare o riassumere grandi quantità di dati in un’unica diapositiva di una presentazione;
- evidenziare schemi e tendenze nei dati;
- dedurre la direzione e lo slancio dei dati nel tempo o rispetto a una specifica unità di misura;
- individuare valori anomali, aberrazioni, deviazioni, errori e dati privi di senso;
- comunicare o presentare dati complessi.
In PowerPoint, è possibile creare grafici attraverso la funzione Inserisci, che fornisce modelli per la progettazione di molti tipi di grafici. Utilizzando Aspose.Slides, è possibile creare sia grafici standard (basati su tipi di grafico popolari) sia grafici personalizzati.
Note
Utilizza l’enumerazione ChartType nel package com.aspose.slides. I valori di questa enumerazione corrispondono a diversi tipi di grafico.Crea grafici a colonne raggruppate
Questo esempio utilizza addChart per creare un grafico a colonne raggruppate che confronta due serie su tre categorie. Le serie utilizzano 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 nel workbook del grafico incorporato.
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:

Crea grafici a dispersione
I grafici a dispersione (noti anche come scatter plot o grafici x‑y) sono spesso usati per verificare schemi o dimostrare correlazioni tra due variabili.
Usa un grafico a dispersione quando:
- Hai dati numerici accoppiati.
- Hai due variabili che si abbinano bene.
- Vuoi determinare se le due variabili sono correlate.
- Hai una variabile indipendente con 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 morbide 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:

Crea grafici a torta
I grafici a torta sono ideali per mostrare la relazione parte‑totale nei dati, specialmente 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 diverse combinazioni di valori, percentuali e informazioni sulla serie. Il metodo setFirstSliceAngle imposta la prima fetta 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().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 fuori dalla torta, vedi Format Leader Lines per un esempio che posiziona le etichette e personalizza colore, larghezza, trasparenza e stile tratteggio delle linee.
Crea grafici a linee
I grafici a linee (noti anche come line graph) sono migliori quando desideri dimostrare variazioni di valore nel tempo. Utilizzando un grafico a linee, puoi confrontare una grande quantità di dati contemporaneamente, tracciare cambiamenti e tendenze nel tempo, evidenziare anomalie nelle serie di dati e altro ancora.
Questo esempio utilizza 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 di un grafico a linee sono collegati da linee continue dritte. Se vuoi che i punti siano collegati da tratti tratteggiati, 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:

Crea 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 delle categorie e le etichette dei genitori sovrapposte 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:

Crea grafici a cascata
Un grafico a cascata mostra come le variazioni positive e negative contribuiscano a un valore finale. Ad esempio, una ripartizione del profitto può partire dal fatturato, sottrarre i costi e aggiungere altri ricavi. Le colonne di variazione fluttuano tra il valore corrente precedente e quello nuovo, mentre le colonne totali si estendono da zero al valore accumulato.
L’esempio seguente utilizza importi in migliaia di dollari statunitensi:
| Categoria | Valore nella cartella di lavoro | Tipo di colonna |
|---|---|---|
| Ricavi | 1000 | Incremento |
| Costo delle vendite | -400 | Decremento |
| Profitto lordo | 600 | Totale intermedio |
| Spese operative | -200 | Decremento |
| Altri ricavi | 50 | Incremento |
| Utile netto | 450 | Totale finale |
Per contrassegnare un punto come totale intermedio o finale, chiama il suo metodo setSetAsTotal con true. Fornisci l’importo accumulato effettivo nella cella del workbook di quel punto: 600 per il profitto lordo (1000 - 400) e 450 per l’utile netto (600 - 200 + 50). Il metodo segna la colonna come totale; non calcola né popola il valore della cella. Non usare 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 completo in Java crea un grafico usando il membro Waterfall di ChartType, cancella i dati predefiniti e riempie il workbook incorporato. L’indice del foglio 0 seleziona il primo foglio; la colonna A contiene i nomi delle categorie e la colonna B contiene i valori. Ogni cella valore è aggiunta con addDataPointForWaterfallSeries. Gli indici dei punti basati su zero 2 e 5 identificano i totali intermedi e finali. Chiamando setShowValue con true si mostrano gli importi sulle colonne. Non è richiesta alcuna presentazione o workbook 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 variazioni aggiuntive.
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 di livello serie setShowConnectorLines con true per mostrare le linee che collegano le colonne consecutive e rendere più facile seguire il valore corrente. Per nascondere queste linee, sostituisci la chiamata al metodo nell’esempio con series.setShowConnectorLines(false); prima di salvare. Questo cambia solo la visibilità della linea, non i dati o i totali.
La presentazione salvata mostra un profitto lordo di 600 e un utile netto di 450, entrambi i totali partendo da zero:

Crea grafici azionari
I grafici azionari sono usati per visualizzare dati finanziari come prezzi di apertura, massimo, minimo e chiusura, aiutando ad analizzare tendenze di mercato e volatilità. Offrono approfondimenti essenziali sulle performance azionarie, supportando investitori e analisti nelle decisioni informate.
Questo esempio crea un grafico open‑high‑low‑close con quattro serie in quell’ordine e tre categorie. Il metodo setUpDownBars abilita le barre su/giù, e getHiLowLinesFormat controlla le linee high‑low che mostrano gli intervalli di prezzo, mentre le linee delle serie individuali e le linee della griglia orizzontale minore sono nascoste.
Il manager restituito da getUpDownBars espone oggetti di formattazione separati tramite getUpBarsFormat e getDownBarsFormat. Usa i metodi getFill e getLine di ogni oggetto per impostare riempimento e contorno in modo indipendente. Questo esempio utilizza barre verdi con contorni verde scuro per gli intervalli in aumento e barre arancione‑rosso con contorni rosso scuro per gli intervalli in diminuzione.
Fornisci valori numerici per tutte e quattro le serie in ciascuna categoria, con High e Low che racchiudono Open e Close. Le barre confrontano Close con Open all’interno della stessa categoria, non con la categoria precedente: A scende da 72 a 25, mentre B sale da 25 a 38 e C sale da 38 a 50. Valori di Open e Close uguali non producono alcun intervallo visibile. Le barre su/giù coprono Open‑Close; le linee high‑low coprono Low‑High. Queste barre appartengono al gruppo serie e non sono serie di grafico a barre ordinarie.
Questa formattazione funziona anche con grafici Line and LineWithMarkers che contengono almeno due serie nello stesso gruppo e valori numerici corrispondenti per ogni categoria. Per questi grafici a linee non impilati, le barre su/giù confrontano la prima e l’ultima serie: un valore finale più alto genera una barra su, un valore finale più basso genera una barra giù. Invertire le serie inverte la classificazione. L’esempio sotto utilizza OpenHighLowClose; non presumere che altre varianti stock, linee impilate o 3D usino la stessa disposizione dei dati o interpretazione degli intervalli.
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.OpenHighLowClose, 20, 20, 500, 150, 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);
IUpDownBarsManager upDownBars = chart.getChartData().getSeriesGroups().get_Item(0).getUpDownBars();
upDownBars.setUpDownBars(true);
upDownBars.getUpBarsFormat().getFill().setFillType(FillType.Solid);
upDownBars.getUpBarsFormat().getFill().getSolidFillColor().setColor(new Color(50, 205, 50));
upDownBars.getUpBarsFormat().getLine().getFillFormat().setFillType(FillType.Solid);
upDownBars.getUpBarsFormat().getLine().getFillFormat().getSolidFillColor().setColor(new Color(0, 100, 0));
upDownBars.getUpBarsFormat().getLine().setWidth(2);
upDownBars.getDownBarsFormat().getFill().setFillType(FillType.Solid);
upDownBars.getDownBarsFormat().getFill().getSolidFillColor().setColor(new Color(255, 69, 0));
upDownBars.getDownBarsFormat().getLine().getFillFormat().setFillType(FillType.Solid);
upDownBars.getDownBarsFormat().getLine().getFillFormat().getSolidFillColor().setColor(new Color(139, 0, 0));
upDownBars.getDownBarsFormat().getLine().setWidth(2);
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, esportato da PowerPoint:

Crea grafici a scatola e baffi
I grafici a scatola e baffi sono usati per mostrare la distribuzione dei dati riassumendo misure statistiche chiave, come mediana, quartili e potenziali outlier. Sono particolarmente utili nell’analisi esplorativa dei dati e negli studi statistici per comprendere rapidamente la variabilità dei dati e identificare eventuali anomalie.
Questo esempio crea un grafico a scatola e baffi da sei valori. Il metodo setQuartileMethod seleziona il calcolo dei quartili esclusivo. L’esempio attiva anche linee della media, marcatori della media, punti interni e 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();
}
Crea grafici a imbuto
I grafici a imbuto sono usati per visualizzare 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 utilizza addChart per aggiungere un grafico a imbuto alla prima diapositiva di una presentazione esistente. Sostituisce i dati predefiniti con sei categorie e valori da 50 a 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:

Crea grafici a raggi
I grafici a raggi sono usati per visualizzare dati gerarchici, mostrando i livelli come anelli concentrici. Aiutano a illustrare relazioni parte‑totale e sono ideali per rappresentare categorie e sotto‑categorie nidificate in modo chiaro e compatto.
Questo esempio crea un grafico a raggi 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 delle categorie 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:

Crea grafici istogramma
Gli istogrammi mostrano come i valori numerici si distribuiscono across intervalli (bin). Per i report mensili sui tempi di elaborazione degli ordini, usa la stessa larghezza del bin e le stesse soglie per mantenere gli intervalli coerenti e rendere più semplice 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.
Usa 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 fornisci 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 visualizzata in PowerPoint mostra 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 pari a 40 rimangono nell’intervallo precedente. I bin interni contengono valori > limite inferiore e ≤ limite superiore.

Specifica il numero di bin
Per un livello di dettaglio fisso anziché 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 confini possono cambiare tra 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 confini differiscono.

Crea grafici radar
I grafici radar sono usati per visualizzare dati multivariati in un formato bidimensionale, consentendo un facile confronto di più variabili simultaneamente. Sono particolarmente utili per identificare schemi, punti di forza e debolezze across più metriche di performance o attributi.
Questo esempio utilizza 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:

Crea grafici multi‑categoria
I grafici multi‑categoria sono usati per visualizzare dati che coinvolgono più raggruppamenti categorici, consentendo di confrontare valori across più dimensioni simultaneamente. Sono particolarmente utili quando è necessario analizzare tendenze e relazioni in dataset 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 che 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:

Rimuovi un’etichetta di trimestre
Scarica quarters.pptx e posizionala nella directory di lavoro. Il suo grafico mostra nove mesi e una singola serie di vendite con valori da 10 a 18. Sull’asse delle categorie, Q1 copre gennaio‑marzo, Q2 aprile‑giugno e Q3 luglio‑settembre.
Aprile è la quarta categoria (indice 3) e contiene l’etichetta Q2. Usa getGroupingLevels per accedere ai livelli di raggruppamento di aprile, quindi chiama deleteGroupingItem con livello 1 per rimuovere la sua etichetta di trimestre. Il livello 0 rappresenta il mese stesso e non può essere rimosso con questo metodo.
import com.aspose.slides.*;
import java.util.StringJoiner;
Presentation presentation = new Presentation("quarters.pptx");
try {
IChart chart = (IChart) presentation.getSlides().get_Item(0).getShapes().get_Item(0);
IChartCategory april = chart.getChartData().getCategories().get_Item(3);
april.getGroupingLevels().deleteGroupingItem(1);
presentation.save("quarters-updated.pptx", SaveFormat.Pptx);
} finally {
presentation.dispose();
}
Presentation reopened = new Presentation("quarters-updated.pptx");
try {
IChart updatedChart = (IChart) reopened.getSlides().get_Item(0).getShapes().get_Item(0);
IChartData data = updatedChart.getChartData();
StringJoiner months = new StringJoiner(", ");
for (IChartCategory month : data.getCategories()) {
months.add(String.valueOf(month.getAsCell().getValue()));
}
StringJoiner sales = new StringJoiner(", ");
for (IChartDataPoint point : data.getSeries().get_Item(0).getDataPoints()) {
sales.add(String.valueOf(point.getValue().getData()));
}
System.out.println(months);
System.out.println(sales);
} finally {
reopened.dispose();
}
Dopo aver riaperto il grafico, l’esempio stampa i mesi originali (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep) e i valori di vendita (10, 11, 12, 13, 14, 15, 16, 17, 18) nello stesso ordine. Apri quarters-updated.pptx in PowerPoint per confrontare le etichette dell’asse. L’etichetta Q2 e il confine del gruppo prima di aprile scompaiono, quindi Q1 copre gennaio‑giugno. Q3 inizia ancora a luglio.

Crea grafici mappa
I grafici mappa sono usati per visualizzare 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 visualmente coinvolgente.
Questo esempio utilizza addChart per creare un grafico mappa 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 mappa e i suoi dati, ma non disegna i grafici mappa di per 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.Crea grafici combinati
Un grafico combinato (o combo chart) combina due o più tipi di grafico in un unico grafico. Questo grafico ti consente di evidenziare, confrontare o esaminare differenze tra due o più insiemi di dati, aiutandoti a identificare le relazioni tra di essi.

Questo esempio combina due serie di colonne raggruppate con una serie a linee across quattro categorie. Le colonne usano l’asse verticale primaria, mentre setPlotOnSecondAxis posiziona la linea su un asse verticale secondario a destra. Le funzioni di supporto configurano titolo, leggenda, etichette degli assi e linee della 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();
Aggiorna i grafici
Aspose.Slides per Java consente di aggiornare i grafici PowerPoint modificando dati, formattazione e stile. Questa funzionalità semplifica il mantenimento delle presentazioni aggiornate con contenuti dinamici e garantisce che i grafici riflettano accuratamente dati e standard visuali attuali.
Questo esempio aggiorna il grafico denominato “My chart” nella prima diapositiva di una presentazione esistente. Richiede due serie di colonne con tre punti dati ciascuna, con etichette di categoria nella colonna A e nomi delle 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();
}
Imposta l’intervallo dati per un grafico
Per ispezionare l’intervallo già utilizzato da un grafico esistente, vedi 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 origine per i dati del tuo grafico. Ciò significa che puoi mappare direttamente una porzione del tuo foglio di lavoro al grafico, controllando quali celle contribuiscono alle serie e alle categorie del grafico. Di conseguenza, puoi aggiornare e sincronizzare facilmente i grafici con le ultime modifiche dei dati nel foglio, assicurando che le tue presentazioni PowerPoint riflettano informazioni attuali e accurate.
Questo esempio utilizza setRange per impostare la fonte dati del grafico denominato “My chart” nella prima diapositiva di una presentazione esistente a Sheet1!A1:B4. Il workbook del grafico deve contenere quel foglio 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();
}
Usa marcatori predefiniti nei grafici
Quando utilizzi marcatori predefiniti nei grafici, ogni serie del grafico ottiene automaticamente un simbolo marcatore predefinito diverso.
Questo esempio utilizza addChart per creare un grafico con due serie a linee e una leggenda. Le impostazioni del marcatore accessibili tramite getMarker mantengono i simboli 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à ti consente di scegliere il tipo di grafico più appropriato per le tue esigenze di visualizzazione dei dati.
Come aggiungo un nuovo grafico a una diapositiva?
Per aggiungere un grafico, prima crei 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 dei dati (IChartDataWorkbook), cancellando eventuali serie e categorie predefinite, e aggiungendo i tuoi dati personalizzati. Questo 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, legende e altri elementi di formattazione per adattare l’aspetto del grafico ai tuoi requisiti di design specifici.
Funzionalità correlata: Create editable charts.