Criar ou Atualizar Gráficos de Apresentação PowerPoint em PHP
Visão geral
Este artigo fornece um guia abrangente sobre como criar e personalizar gráficos usando Aspose.Slides for PHP via Java. Você aprenderá a adicionar programaticamente um gráfico a um slide, preenchê‑lo com dados e aplicar várias opções de formatação para atender aos seus requisitos de design específicos. Ao longo do artigo, exemplos de código detalhados ilustram cada etapa, desde a inicialização da apresentação e do objeto de gráfico até a configuração de séries, eixos e legendas. Seguindo este guia, você obterá uma compreensão sólida de como integrar a geração dinâmica de gráficos em suas aplicações PHP, simplificando o processo de criação de apresentações orientadas a dados.
Criar um Gráfico
Gráficos ajudam as pessoas a visualizar rapidamente dados e obter insights que podem não ser imediatamente óbvios a partir de uma tabela ou planilha.
Por que criar gráficos?
Usando gráficos, você pode:
- agregar, condensar ou resumir grandes volumes de dados em um único slide de uma apresentação;
- revelar padrões e tendências nos dados;
- deduzir a direção e o impulso dos dados ao longo do tempo ou em relação a uma unidade de medida específica;
- identificar valores atípicos, aberrações, desvios, erros e dados sem sentido;
- comunicar ou apresentar dados complexos.
No PowerPoint, você pode criar gráficos através da função Insert, que oferece modelos para projetar muitos tipos de gráficos. Usando Aspose.Slides, você pode criar tanto gráficos regulares (baseados em tipos de gráfico populares) quanto gráficos personalizados.
Note
Use a enumeração ChartType no namespace aspose\slides. Os valores desta enumeração correspondem a diferentes tipos de gráficos.Criar Gráficos de Colunas Agrupadas
Este exemplo usa addChart para criar um gráfico de colunas agrupadas que compara duas séries em três categorias. As séries usam preenchimentos vermelho e verde, e os rótulos individuais demonstram nomes de categorias, nomes de séries e valores. O índice da planilha 0 refere‑se à primeira planilha do workbook de gráfico incorporado.
use aspose\slides\ChartType;
use aspose\slides\FillType;
use aspose\slides\NullableBool;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$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);
$workbook = $chart->getChartData()->getChartDataWorkbook();
$worksheetIndex = 0;
$chart->getChartData()->getSeries()->clear();
$chart->getChartData()->getCategories()->clear();
$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());
$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);
$series = $chart->getChartData()->getSeries()->get_Item(0);
$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);
$color = new Java("java.awt.Color", 255, 0, 0);
$series->getFormat()->getFill()->getSolidFillColor()->setColor($color);
$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);
$color = new Java("java.awt.Color", 0, 128, 0);
$series->getFormat()->getFill()->getSolidFillColor()->setColor($color);
$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();
}
O resultado:

Criar Gráficos de Dispersão
Gráficos de dispersão (também conhecidos como scatter plots ou gráficos x‑y) são frequentemente usados para verificar padrões ou demonstrar correlações entre duas variáveis.
Use um gráfico de dispersão quando:
- Você tem dados numéricos pareados.
- Você tem duas variáveis que se combinam bem.
- Você deseja determinar se as duas variáveis estão relacionadas.
- Você tem uma variável independente que possui múltiplos valores para uma variável dependente.
Este exemplo traça dois conjuntos de valores x‑y. A primeira série usa linhas retas com marcadores de estrela, enquanto a segunda usa linhas suaves com marcadores de círculo; ambas usam um tamanho de marcador de 10, configurado com setSize. O método setSymbol controla a forma do marcador.
use aspose\slides\ChartType;
use aspose\slides\MarkerStyleType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$chart = $slide->getShapes()->addChart(ChartType::ScatterWithSmoothLines, 20, 20, 500, 300);
$workbook = $chart->getChartData()->getChartDataWorkbook();
$worksheetIndex = 0;
$chart->getChartData()->getSeries()->clear();
$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());
$series = $chart->getChartData()->getSeries()->get_Item(0);
$xValueCell = $workbook->getCell($worksheetIndex, 2, 1, 1);
$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();
}
O resultado:

Criar Gráficos de Pizza
Gráficos de pizza são mais adequados para mostrar a relação parte‑para‑todo nos dados, especialmente quando os dados contêm rótulos categóricos com valores numéricos. Contudo, se seus dados contiverem muitas partes ou rótulos, talvez seja melhor usar um gráfico de barras.
Este exemplo cria um gráfico de pizza com três valores trimestrais. Cada fatia tem um preenchimento e borda personalizados, e os rótulos exibem diferentes combinações de valores, percentuais e informações de série. O método setFirstSliceAngle define a primeira fatia para iniciar em 180 graus.
use aspose\slides\ChartType;
use aspose\slides\FillType;
use aspose\slides\LineDashStyle;
use aspose\slides\LineStyle;
use aspose\slides\NullableBool;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$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);
$workbook = $chart->getChartData()->getChartDataWorkbook();
$worksheetIndex = 0;
$chart->getChartData()->getSeries()->clear();
$chart->getChartData()->getCategories()->clear();
$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);
$seriesNameCell = $workbook->getCell(0, 0, 1, "Series 1");
$series = $chart->getChartData()->getSeries()->add($seriesNameCell, $chart->getType());
$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);
$firstSlice = $series->getDataPoints()->get_Item(0);
$firstSlice->getFormat()->getFill()->setFillType(FillType::Solid);
$color = new Java("java.awt.Color", 0, 255, 255);
$firstSlice->getFormat()->getFill()->getSolidFillColor()->setColor($color);
$firstSlice->getFormat()->getLine()->getFillFormat()->setFillType(FillType::Solid);
$color = new Java("java.awt.Color", 128, 128, 128);
$firstSlice->getFormat()->getLine()->getFillFormat()->getSolidFillColor()->setColor($color);
$firstSlice->getFormat()->getLine()->setWidth(3.0);
$firstSlice->getFormat()->getLine()->setStyle(LineStyle::ThinThick);
$firstSlice->getFormat()->getLine()->setDashStyle(LineDashStyle::LargeDash);
$secondSlice = $series->getDataPoints()->get_Item(1);
$secondSlice->getFormat()->getFill()->setFillType(FillType::Solid);
$color = new Java("java.awt.Color", 165, 42, 42);
$secondSlice->getFormat()->getFill()->getSolidFillColor()->setColor($color);
$secondSlice->getFormat()->getLine()->getFillFormat()->setFillType(FillType::Solid);
$color = new Java("java.awt.Color", 0, 0, 255);
$secondSlice->getFormat()->getLine()->getFillFormat()->getSolidFillColor()->setColor($color);
$secondSlice->getFormat()->getLine()->setWidth(3.0);
$secondSlice->getFormat()->getLine()->setStyle(LineStyle::Single);
$secondSlice->getFormat()->getLine()->setDashStyle(LineDashStyle::LargeDashDot);
$thirdSlice = $series->getDataPoints()->get_Item(2);
$thirdSlice->getFormat()->getFill()->setFillType(FillType::Solid);
$color = new Java("java.awt.Color", 255, 127, 80);
$thirdSlice->getFormat()->getFill()->getSolidFillColor()->setColor($color);
$thirdSlice->getFormat()->getLine()->getFillFormat()->setFillType(FillType::Solid);
$color = new Java("java.awt.Color", 255, 0, 0);
$thirdSlice->getFormat()->getLine()->getFillFormat()->getSolidFillColor()->setColor($color);
$thirdSlice->getFormat()->getLine()->setWidth(2.0);
$thirdSlice->getFormat()->getLine()->setStyle(LineStyle::ThinThin);
$thirdSlice->getFormat()->getLine()->setDashStyle(LineDashStyle::LargeDashDotDot);
$firstLabel = $series->getDataPoints()->get_Item(0)->getLabel();
$firstLabel->getDataLabelFormat()->setShowValue(true);
$secondLabel = $series->getDataPoints()->get_Item(1)->getLabel();
$secondLabel->getDataLabelFormat()->setShowValue(true);
$secondLabel->getDataLabelFormat()->setShowLegendKey(true);
$secondLabel->getDataLabelFormat()->setShowPercentage(true);
$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();
}
O resultado:

Para melhorar a legibilidade dos rótulos fora da pizza, veja Formatar linhas de ligação para um exemplo que posiciona rótulos e personaliza a cor, largura, transparência e estilo tracejado das linhas.
Criar Gráficos de Linhas
Gráficos de linhas (também conhecidos como line graphs) são mais adequados em situações onde você deseja demonstrar mudanças de valor ao longo do tempo. Usando um gráfico de linhas, você pode comparar uma grande quantidade de dados de uma só vez, rastrear mudanças e tendências ao longo do tempo, destacar anomalias em séries de dados e muito mais.
Este exemplo usa addChart para criar um gráfico de linhas com as séries e categorias padrão, e então salva a apresentação como PPTX.
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$lineChart = $slide->getShapes()->addChart(ChartType::Line, 20, 20, 500, 300);
$presentation->save("lineChart.pptx", SaveFormat::Pptx);
}
finally
{
$presentation->dispose();
}
Por padrão, os pontos em um gráfico de linhas são ligados por linhas retas contínuas. Se você quiser que os pontos sejam ligados por traços, chame setDashStyle com um valor de LineDashStyle:
use aspose\slides\ChartType;
use aspose\slides\LineDashStyle;
use aspose\slides\Presentation;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$lineChart = $slide->getShapes()->addChart(ChartType::Line, 20, 20, 500, 300);
for ($i = 0; $i < java_values($lineChart->getChartData()->getSeries()->size()); $i++)
{
$series = $lineChart->getChartData()->getSeries()->get_Item($i);
$series->getFormat()->getLine()->setDashStyle(LineDashStyle::Dash);
}
}
finally
{
$presentation->dispose();
}
O resultado:

Criar Gráficos de Mapa de Árvore
Gráficos de mapa de árvore são mais adequados para dados de vendas quando você deseja mostrar o tamanho relativo das categorias de dados e chamar rapidamente a atenção para itens que são grandes contribuintes dentro de cada categoria.
Este exemplo cria um mapa de árvore com oito folhas agrupadas em quatro troncos e dois ramos. O método setGroupingItem atribui troncos ao nível de agrupamento 1 e ramos ao nível 2. Os valores determinam os tamanhos relativos dos retângulos, enquanto os rótulos de categoria e os rótulos de pais sobrepostos identificam a hierarquia.
use aspose\slides\ChartType;
use aspose\slides\ParentLabelLayoutType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$chart = $slide->getShapes()->addChart(ChartType::Treemap, 20, 20, 500, 300);
$chart->getChartData()->getCategories()->clear();
$chart->getChartData()->getSeries()->clear();
$workbook = $chart->getChartData()->getChartDataWorkbook();
$workbook->clear(0);
// Ramo 1
$categoryCell = $workbook->getCell(0, "C1", "Leaf1");
$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);
$series = $chart->getChartData()->getSeries()->add(ChartType::Treemap);
$series->getLabels()->getDefaultDataLabelFormat()->setShowCategoryName(true);
$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();
}
O resultado:

Criar Gráficos de Cascata
Um gráfico de cascata mostra como mudanças positivas e negativas contribuem para um valor final. Por exemplo, uma análise de lucro pode começar com a receita, subtrair custos e adicionar outras receitas. As colunas de mudança flutuam entre os valores acumulados anteriores e novos, enquanto as colunas totais se estendem de zero ao valor acumulado.
O exemplo a seguir usa valores em milhares de dólares americanos:
| Categoria | Valor da planilha | Tipo de coluna |
|---|---|---|
| Receita | 1000 | Aumento |
| Custo de vendas | -400 | Redução |
| Lucro bruto | 600 | Total intermediário |
| Despesas operacionais | -200 | Redução |
| Outras receitas | 50 | Aumento |
| Lucro líquido | 450 | Total final |
Para marcar um ponto como total intermediário ou final, chame seu método setSetAsTotal com true. Forneça o valor acumulado real na célula da planilha desse ponto: 600 para lucro bruto (1000 - 400) e 450 para lucro líquido (600 - 200 + 50). O método marca a coluna como total; ele não calcula nem preenche o valor da célula. Não use zero como marcador ou forneça outra mudança para um ponto total. Uma coluna total exibe o valor acumulado sem adicioná‑lo novamente ao valor corrente.
Este exemplo PHP completo cria um gráfico usando o membro Waterfall de ChartType, limpa os dados padrão e preenche o workbook incorporado. O índice da planilha 0 seleciona a primeira planilha; a coluna A contém nomes de categorias e a coluna B contém valores. Cada célula de valor é adicionada com addDataPointForWaterfallSeries. Os índices de ponto baseados em zero 2 e 5 identificam os totais intermediário e final. Chamando setShowValue com true exibe os valores nas colunas. Nenhuma apresentação ou workbook de entrada é necessário.
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$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();
$workbook = $chart->getChartData()->getChartDataWorkbook();
$worksheetIndex = 0;
$workbook->clear($worksheetIndex);
$seriesNameCell = $workbook->getCell($worksheetIndex, 0, 1, "Profit");
$series = $chart->getChartData()->getSeries()->add($seriesNameCell, ChartType::Waterfall);
$categories = [ "Revenue", "Cost of sales", "Gross profit", "Operating expenses", "Other income", "Net profit" ];
$values = [ 1000, -400, 600, -200, 50, 450 ];
for ($i = 0; $i < count($categories); $i++)
{
$categoryCell = $workbook->getCell($worksheetIndex, $i + 1, 0, $categories[$i]);
$chart->getChartData()->getCategories()->add($categoryCell);
$valueCell = $workbook->getCell($worksheetIndex, $i + 1, 1, $values[$i]);
$series->getDataPoints()->addDataPointForWaterfallSeries($valueCell);
}
// Os pontos terceiro e sexto representam totais, não alterações adicionais.
$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();
}
Chame o método de nível de série setShowConnectorLines com true para mostrar linhas que ligam colunas consecutivas e facilitar o acompanhamento do valor corrente. Para ocultar essas linhas, substitua a chamada de método no exemplo por $series->setShowConnectorLines(false); antes de salvar. Isso altera apenas a visibilidade da linha, não os dados ou os totais.
A apresentação salva mostra lucro bruto de 600 e lucro líquido de 450, com ambos os totais desenhados a partir de zero:

Criar Gráficos de Ações
Gráficos de ações são usados para exibir dados financeiros como preços de abertura, alta, baixa e fechamento, ajudando a analisar tendências de mercado e volatilidade. Eles oferecem insights essenciais sobre o desempenho das ações, auxiliando investidores e analistas a tomar decisões informadas.
Este exemplo cria um gráfico OHLC (open‑high‑low‑close) com quatro séries nessa ordem e três categorias. O método setUpDownBars habilita barras de alta/baixa, e getHiLowLinesFormat controla as linhas alta‑baixa que mostram a faixa de preços, enquanto as linhas individuais das séries e as linhas de grade horizontais menores são ocultas.
use aspose\slides\ChartType;
use aspose\slides\FillType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$chart = $slide->getShapes()->addChart(ChartType::OpenHighLowClose, 20, 20, 500, 300, false);
$workbook = $chart->getChartData()->getChartDataWorkbook();
$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);
$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);
$series = $chart->getChartData()->getSeries()->get_Item(0);
$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 ($i = 0; $i < java_values($chart->getChartData()->getSeries()->size()); $i++)
{
$stockSeries = $chart->getChartData()->getSeries()->get_Item($i);
$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();
}
O resultado:

Criar Gráficos de Caixa e Bigodes
Gráficos de caixa e bigodes são usados para exibir a distribuição de dados resumindo medidas estatísticas chave, como a mediana, quartis e possíveis valores atípicos. Eles são particularmente úteis em análises exploratórias de dados e estudos estatísticos para entender rapidamente a variabilidade dos dados e identificar anomalias.
Este exemplo cria um gráfico de caixa e bigodes a partir de seis valores. O método setQuartileMethod seleciona o cálculo de quartil exclusivo. O exemplo também habilita linhas de média, marcadores de média, pontos internos e pontos atípicos.
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\QuartileMethodType;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$chart = $slide->getShapes()->addChart(ChartType::BoxAndWhisker, 20, 20, 500, 300);
$chart->getChartData()->getCategories()->clear();
$chart->getChartData()->getSeries()->clear();
$workbook = $chart->getChartData()->getChartDataWorkbook();
$workbook->clear(0);
$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);
$series = $chart->getChartData()->getSeries()->add(ChartType::BoxAndWhisker);
$series->setQuartileMethod(QuartileMethodType::Exclusive);
$series->setShowMeanLine(true);
$series->setShowMeanMarkers(true);
$series->setShowInnerPoints(true);
$series->setShowOutlierPoints(true);
$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();
}
Criar Gráficos de Funil
Gráficos de funil são usados para visualizar processos que envolvem estágios sequenciais, onde o volume de dados diminui à medida que avança de uma etapa para a próxima. Eles são especialmente úteis para analisar taxas de conversão, identificar gargalos e acompanhar a eficiência de processos de vendas ou marketing.
Este exemplo usa addChart para adicionar um gráfico de funil ao primeiro slide de uma apresentação existente. Ele substitui os dados padrão por seis categorias e valores que variam de 50 a 500, e então salva a apresentação atualizada. A apresentação de entrada deve conter ao menos um slide.
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation("test.pptx");
try
{
$slide = $presentation->getSlides()->get_Item(0);
$chart = $slide->getShapes()->addChart(ChartType::Funnel, 50, 50, 500, 400);
$chart->getChartData()->getCategories()->clear();
$chart->getChartData()->getSeries()->clear();
$workbook = $chart->getChartData()->getChartDataWorkbook();
$workbook->clear(0);
$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);
$series = $chart->getChartData()->getSeries()->add(ChartType::Funnel);
$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();
}
O resultado:

Criar Gráficos de Explosão Circular
Gráficos de explosão circular são usados para visualizar dados hierárquicos, exibindo níveis como anéis concêntricos. Eles ajudam a ilustrar relações parte‑para‑todo e são ideais para representar categorias e subcategorias aninhadas de forma clara e compacta.
Este exemplo cria um gráfico de explosão circular com oito folhas agrupadas em quatro troncos e dois ramos. O método setGroupingItem atribui troncos ao nível de agrupamento 1 e ramos ao nível 2. Os rótulos de categoria identificam os segmentos, e os valores determinam seus tamanhos relativos.
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$chart = $slide->getShapes()->addChart(ChartType::Sunburst, 20, 20, 500, 300);
$chart->getChartData()->getCategories()->clear();
$chart->getChartData()->getSeries()->clear();
$workbook = $chart->getChartData()->getChartDataWorkbook();
$workbook->clear(0);
// Ramo 1
$categoryCell = $workbook->getCell(0, "C1", "Leaf1");
$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);
$series = $chart->getChartData()->getSeries()->add(ChartType::Sunburst);
$series->getLabels()->getDefaultDataLabelFormat()->setShowCategoryName(true);
$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();
}
O resultado:

Criar Gráficos de Histograma
Gráficos de histograma mostram como valores numéricos são distribuídos em intervalos (bins). Para relatórios mensais sobre tempos de processamento de pedidos, use a mesma largura de bin e limites para manter os intervalos consistentes e tornar as distribuições mais fáceis de comparar.
Chame setAggregationType no eixo horizontal com um modo de AxisAggregationType. setBinWidth aplica‑se apenas a ByBinWidth; setNumberOfBins aplica‑se apenas a ByNumberOfBins. Use Automatic para deixar o gráfico escolher os bins.
Usar Largura de Bin Fixa
Este exemplo agrupa tempos de processamento em intervalos de 10 minutos, com bins separados para tempos de até 10 minutos e acima de 40 minutos. Ative esses bins com setUnderflowBin e setOverflowBin. Ao fornecer limites explícitos por meio de setUnderflowBin e setOverflowBin, chame setAutomaticUnderflowBin e setAutomaticOverflowBin com false.
use aspose\slides\AxisAggregationType;
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$chart = $slide->getShapes()->addChart(ChartType::Histogram, 20, 20, 680, 200);
$chart->setLegend(false);
$chart->setTitle(false);
$chart->getChartData()->getCategories()->clear();
$chart->getChartData()->getSeries()->clear();
$workbook = $chart->getChartData()->getChartDataWorkbook();
$workbook->clear(0);
$series = $chart->getChartData()->getSeries()->add(ChartType::Histogram);
$values = [ 5, 10, 10, 11, 15, 20, 20, 21, 25, 30, 30, 31, 35, 40, 40, 41, 50 ];
for ($i = 0; $i < count($values); $i++)
{
$valueCell = $workbook->getCell(0, $i, 0, $values[$i]);
$series->getDataPoints()->addDataPointForHistogramSeries($valueCell);
}
$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();
}
A apresentação exibida no PowerPoint mostra contagens de bins 3, 4, 4, 4 e 2. O bin de subfluxo inclui 5, 10, 10, portanto seu limite é inclusivo. O bin de transbordamento inclui apenas 41, 50, portanto seu limite é exclusivo; ambos os valores iguais a 40 permanecem no intervalo anterior. Os bins internos contêm valores maiores que seu limite inferior e menores ou iguais ao seu limite superior.

Especificar o Número de Bins
Para um nível fixo de detalhe em vez de intervalos fixos, solicite cinco bins para os mesmos dados. Este exemplo deixa os bins de subfluxo e transbordamento desativados. O gráfico determina a largura a partir do intervalo de dados, portanto os limites podem mudar entre relatórios.
use aspose\slides\AxisAggregationType;
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$chart = $slide->getShapes()->addChart(ChartType::Histogram, 20, 20, 680, 200);
$chart->setLegend(false);
$chart->setTitle(false);
$chart->getChartData()->getCategories()->clear();
$chart->getChartData()->getSeries()->clear();
$workbook = $chart->getChartData()->getChartDataWorkbook();
$workbook->clear(0);
$series = $chart->getChartData()->getSeries()->add(ChartType::Histogram);
$values = [ 5, 10, 10, 11, 15, 20, 20, 21, 25, 30, 30, 31, 35, 40, 40, 41, 50 ];
for ($i = 0; $i < count($values); $i++)
{
$valueCell = $workbook->getCell(0, $i, 0, $values[$i]);
$series->getDataPoints()->addDataPointForHistogramSeries($valueCell);
}
$axis = $chart->getAxes()->getHorizontalAxis();
$axis->setAggregationType(AxisAggregationType::ByNumberOfBins);
$axis->setNumberOfBins(5);
$presentation->save("Histogram-bin-count.pptx", SaveFormat::Pptx);
}
finally
{
$presentation->dispose();
}
Os cinco bins têm contagens de 4, 4, 4, 4 e 1. Compare esta distribuição com o resultado de largura fixa acima: os valores de entrada são idênticos, mas os limites diferem.

Criar Gráficos Radar
Gráficos radar são usados para exibir dados multivariados em um formato bidimensional, permitindo fácil comparação de várias variáveis simultaneamente. Eles são particularmente úteis para identificar padrões, pontos fortes e fracos em múltiplas métricas de desempenho ou atributos.
Este exemplo usa addChart para criar um gráfico radar com as séries e categorias padrão, e então salva a apresentação como PPTX.
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$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();
}
O resultado:

Criar Gráficos de Múltiplas Categorias
Gráficos de múltiplas categorias são usados para exibir dados que envolvem mais de um agrupamento categórico, permitindo comparar valores em várias dimensões simultaneamente. Eles são particularmente úteis quando você precisa analisar tendências e relacionamentos dentro de conjuntos de dados complexos e multilaterais.
Este exemplo cria um gráfico de colunas agrupadas com oito categorias dispostas em quatro pares. O método setGroupingItem fornece a cada par um rótulo compartilhado no nível de agrupamento 1, produzindo um eixo de categoria com rótulos individuais e de grupo.
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$chart = $slide->getShapes()->addChart(ChartType::ClusteredColumn, 20, 20, 500, 300);
$chart->getChartData()->getSeries()->clear();
$chart->getChartData()->getCategories()->clear();
$workbook = $chart->getChartData()->getChartDataWorkbook();
$workbook->clear(0);
$worksheetIndex = 0;
$categoryCell = $workbook->getCell(0, "c2", "A");
$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);
$seriesNameCell = $workbook->getCell(0, "D1", "Series 1");
$series = $chart->getChartData()->getSeries()->add($seriesNameCell, ChartType::ClusteredColumn);
$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();
}
O resultado:

Criar Gráficos de Mapa
Gráficos de mapa são usados para visualizar dados geográficos ao mapear informações para locais específicos, como países, estados ou cidades. Eles são particularmente úteis para analisar tendências regionais, dados demográficos e distribuições espaciais de maneira clara e visualmente atraente.
Este exemplo usa addChart para criar um gráfico de mapa com os dados geográficos padrão e o salva para visualização no PowerPoint.
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$chart = $slide->getShapes()->addChart(ChartType::Map, 20, 20, 500, 300);
$presentation->save("mapChart.pptx", SaveFormat::Pptx);
}
finally
{
$presentation->dispose();
}
O resultado:

Note
A imagem acima mostra a apresentação salva aberta no PowerPoint. Aspose.Slides grava o gráfico de mapa e seus dados corretamente, mas não desenha gráficos de mapa por conta própria: quando um slide que contém um gráfico de mapa é renderizado para imagem ou convertido em PDF ou SVG, a área do gráfico aparece em branco. Outras formas no mesmo slide não são afetadas.Criar Gráficos de Combinação
Um gráfico de combinação (ou combo chart) combina dois ou mais tipos de gráfico em um único gráfico. Este gráfico permite que você destaque, compare ou examine diferenças entre dois ou mais conjuntos de dados, ajudando a identificar relações entre eles.

Este exemplo combina duas séries de colunas agrupadas com uma série de linha em quatro categorias. As colunas usam o eixo vertical primário, enquanto setPlotOnSecondAxis coloca a linha em um eixo vertical secundário à direita. As funções auxiliares configuram o título, a legenda, os rótulos dos eixos e as linhas de grade.
use aspose\slides\AxisPositionType;
use aspose\slides\ChartType;
use aspose\slides\CrossesType;
use aspose\slides\FillType;
use aspose\slides\LegendPositionType;
use aspose\slides\NullableBool;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
function createComboChart()
{
$presentation = new Presentation();
try
{
$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();
}
}
function createChartWithFirstSeries($slide)
{
$chart = $slide->getShapes()->addChart(ChartType::ClusteredColumn, 50, 50, 600, 400);
$chart->setTitle(true);
$chart->getChartTitle()->addTextFrameForOverriding("Chart Title");
$chart->getChartTitle()->setOverlay(false);
$portionFormat = $chart->getChartTitle()->getTextFrameForOverriding()->getParagraphs()->get_Item(0)->getParagraphFormat()->getDefaultPortionFormat();
$portionFormat->setFontBold(NullableBool::False);
$portionFormat->setFontHeight(18);
$chart->getLegend()->setPosition(LegendPositionType::Bottom);
$chart->getLegend()->getTextFormat()->getPortionFormat()->setFontHeight(12);
$chart->getChartData()->getSeries()->clear();
$chart->getChartData()->getCategories()->clear();
$workbook = $chart->getChartData()->getChartDataWorkbook();
$worksheetIndex = 0;
$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);
$seriesNameCell = $workbook->getCell($worksheetIndex, 0, 1, "Series 1");
$series = $chart->getChartData()->getSeries()->add($seriesNameCell, $chart->getType());
$series->getParentSeriesGroup()->setOverlap(-25);
$series->getParentSeriesGroup()->setGapWidth(220);
$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;
}
function addSecondSeriesToChart($chart)
{
$workbook = $chart->getChartData()->getChartDataWorkbook();
$worksheetIndex = 0;
$seriesNameCell = $workbook->getCell($worksheetIndex, 0, 2, "Series 2");
$series = $chart->getChartData()->getSeries()->add($seriesNameCell, ChartType::ClusteredColumn);
$series->getParentSeriesGroup()->setOverlap(-25);
$series->getParentSeriesGroup()->setGapWidth(220);
$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);
}
function addThirdSeriesToChart($chart)
{
$workbook = $chart->getChartData()->getChartDataWorkbook();
$worksheetIndex = 0;
$seriesNameCell = $workbook->getCell($worksheetIndex, 0, 3, "Series 3");
$series = $chart->getChartData()->getSeries()->add($seriesNameCell, ChartType::Line);
$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);
}
function setPrimaryAxesFormat($chart)
{
$horizontalAxis = $chart->getAxes()->getHorizontalAxis();
$horizontalAxis->getTextFormat()->getPortionFormat()->setFontHeight(12);
$horizontalAxis->getFormat()->getLine()->getFillFormat()->setFillType(FillType::NoFill);
setAxisTitle($horizontalAxis, "X Axis");
$verticalAxis = $chart->getAxes()->getVerticalAxis();
$verticalAxis->getTextFormat()->getPortionFormat()->setFontHeight(12);
$verticalAxis->getFormat()->getLine()->getFillFormat()->setFillType(FillType::NoFill);
setAxisTitle($verticalAxis, "Y Axis 1");
$majorGridLinesFormat = $verticalAxis->getMajorGridLinesFormat()->getLine()->getFillFormat();
$majorGridLinesFormat->setFillType(FillType::Solid);
$color = new Java("java.awt.Color", 217, 217, 217);
$majorGridLinesFormat->getSolidFillColor()->setColor($color);
}
function setSecondaryAxesFormat($chart)
{
$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);
$secondaryVerticalAxis = $chart->getAxes()->getSecondaryVerticalAxis();
$secondaryVerticalAxis->setPosition(AxisPositionType::Right);
$secondaryVerticalAxis->getTextFormat()->getPortionFormat()->setFontHeight(12);
$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");
}
function setAxisTitle($axis, $axisTitle)
{
$axis->setTitle(true);
$axis->getTitle()->setOverlay(false);
$titlePortionFormat = $axis->getTitle()->addTextFrameForOverriding($axisTitle)->getParagraphs()->get_Item(0)->getParagraphFormat()->getDefaultPortionFormat();
$titlePortionFormat->setFontBold(NullableBool::False);
$titlePortionFormat->setFontHeight(12);
}
createComboChart();
Atualizar Gráficos
Aspose.Slides for PHP via Java permite que você atualize gráficos do PowerPoint modificando dados, formatação e estilo do gráfico. Essa funcionalidade simplifica o processo de manter apresentações atualizadas com conteúdo dinâmico e garante que os gráficos reflitam com precisão os dados atuais e os padrões visuais.
Este exemplo atualiza o gráfico denominado “My chart” no primeiro slide de uma apresentação existente. Ele requer duas séries de colunas com três pontos de dados cada, com rótulos de categoria na coluna A e nomes de séries na primeira linha da primeira planilha. O exemplo usa getCell para alterar células do workbook, atualiza valores das séries, adiciona uma terceira série e altera o gráfico para cilindros agrupados por meio de setType.
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$chartName = "My chart";
$chartClass = new JavaClass("com.aspose.slides.IChart");
$presentation = new Presentation("ExistingChart.pptx");
try
{
$slide = $presentation->getSlides()->get_Item(0);
for ($i = 0; $i < java_values($slide->getShapes()->size()); $i++)
{
$shape = $slide->getShapes()->get_Item($i);
if (java_instanceof($shape, $chartClass) && $chartName === java_values($shape->getName()))
{
$chart = $shape;
$worksheetIndex = 0;
$workbook = $chart->getChartData()->getChartDataWorkbook();
$workbook->getCell($worksheetIndex, 1, 0, "Modified Category 1");
$workbook->getCell($worksheetIndex, 2, 0, "Modified Category 2");
$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);
$seriesNameCell = $workbook->getCell($worksheetIndex, 0, 3, "Series 3");
$series = $chart->getChartData()->getSeries()->add($seriesNameCell, $chart->getType());
$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();
}
Definir Intervalo de Dados para um Gráfico
Para inspecionar o intervalo já usado por um gráfico existente, veja Retrieve a Chart’s Data Range.
Aspose.Slides for PHP via Java oferece a flexibilidade de definir um intervalo de dados específico de uma planilha como origem para os dados do seu gráfico. Isso significa que você pode mapear diretamente uma parte da sua planilha para o gráfico, permitindo controlar quais células contribuem para as séries e categorias do gráfico. Como resultado, você pode atualizar e sincronizar facilmente seus gráficos com as alterações mais recentes nos dados da planilha, garantindo que suas apresentações PowerPoint reflitam informações atuais e precisas.
Este exemplo usa setRange para definir a fonte de dados do gráfico denominado “My chart” no primeiro slide de uma apresentação existente para Sheet1!A1:B4. O workbook do gráfico deve conter essa planilha e um intervalo populado com um cabeçalho de série na primeira linha, rótulos de categoria na coluna A e três valores na coluna B.
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$chartName = "My chart";
$chartClass = new JavaClass("com.aspose.slides.IChart");
$presentation = new Presentation("ExistingChart.pptx");
try
{
$slide = $presentation->getSlides()->get_Item(0);
for ($i = 0; $i < java_values($slide->getShapes()->size()); $i++)
{
$shape = $slide->getShapes()->get_Item($i);
if (java_instanceof($shape, $chartClass) && $chartName === java_values($shape->getName()))
{
$chart = $shape;
$chart->getChartData()->setRange("Sheet1!A1:B4");
}
}
$presentation->save("SetDataRange.pptx", SaveFormat::Pptx);
}
finally
{
$presentation->dispose();
}
Usar Marcadores Padrão em Gráficos
Quando você usa marcadores padrão em gráficos, cada série de gráfico recebe automaticamente um símbolo de marcador padrão diferente.
Este exemplo usa addChart para criar um gráfico com duas séries de linha e uma legenda. As configurações de marcador acessadas por meio de getMarker mantêm os símbolos de marcador atribuídos automaticamente. A primeira série inclui um valor negativo e um valor ausente, representado por null, enquanto a segunda tem um valor para cada categoria.
use aspose\slides\ChartType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
$presentation = new Presentation();
try
{
$slide = $presentation->getSlides()->get_Item(0);
$chart = $slide->getShapes()->addChart(ChartType::LineWithMarkers, 10, 10, 400, 400);
$chart->getChartData()->getSeries()->clear();
$chart->getChartData()->getCategories()->clear();
$workbook = $chart->getChartData()->getChartDataWorkbook();
$seriesNameCell = $workbook->getCell(0, 0, 1, "Series 1");
$series = $chart->getChartData()->getSeries()->add($seriesNameCell, $chart->getType());
$categoryCell = $workbook->getCell(0, 1, 0, "C1");
$chart->getChartData()->getCategories()->add($categoryCell);
$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");
$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
Quais tipos de gráfico são suportados pelo Aspose.Slides for PHP via Java?
Aspose.Slides for PHP via Java suporta uma ampla variedade de tipos de gráfico, incluindo barra, linha, pizza, área, dispersão, histograma, radar e muitos outros. Essa flexibilidade permite que você escolha o tipo de gráfico mais adequado às necessidades de visualização dos seus dados.
Como adiciono um novo gráfico a um slide?
Para adicionar um gráfico, primeiro crie uma instância da classe Presentation, recupere o slide desejado usando seu índice e então chame o método para adicionar um gráfico, especificando o tipo de gráfico e os dados iniciais. Esse processo integra o gráfico diretamente na sua apresentação.
Como posso atualizar os dados exibidos em um gráfico?
Você pode atualizar os dados de um gráfico acessando seu workbook de dados (ChartDataWorkbook), limpando quaisquer séries e categorias padrão e, em seguida, adicionando seus dados personalizados. Isso permite atualizar programaticamente o gráfico para refletir os dados mais recentes.
É possível personalizar a aparência do gráfico?
Sim, Aspose.Slides for PHP via Java oferece amplas opções de personalização. Você pode modificar cores, fontes, rótulos, legendas e outros elementos de formatação para adaptar a aparência do gráfico aos seus requisitos de design específicos.