Contenido

# Servicio SFDocuments.Chart

The Chart service provides a set of properties and methods to handle charts in Calc documents. With this service it is possible to:

- Acceder a los objetos de gráfico en los documentos de Calc y manipular sus propiedades.

- Crear e insertar gráficos nuevos en un documento de Calc.

- Exportar los gráficos como archivos de imagen.

## Nombres de gráfico

Los gráficos pueden tener dos nombres diferentes:

- Un nombre interno que LibreOffice otorga en cuanto se crea el objeto del gráfico (normalmente «Objeto 1», «Objeto 2», y así sucesivamente).

- Un nombre personalizado que puede definirse al pulsar con el botón secundario del ratón sobre el gráfico y eligiendo Nombre en el menú contextual.

El servicio Chart utiliza principalmente el nombre definido por el usuario para acceder a un objeto de gráfico. Si no existe, se utiliza el nombre interno.

## Invocación del servicio

Antes de utilizar el servicio Chart, es necesario cargar o importar la biblioteca ScriptForge:

• Para cargar la biblioteca ScriptForge que necesitan las macros de Basic se debe usar la siguiente declaración:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
• Los scripts de Python necesitan importar el módulo scriptforge:
from scriptforge import CreateScriptService

The Chart service is instantiated from a Calc service instance either using the Charts or CreateChart methods.

##### En BASIC

The example below creates a Chart service instance from an existing chart in the current Calc document:

        GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
        Dim oDoc as Object, oChart as Object
        Set oDoc = CreateScriptService("Calc")
        Set oChart = oDoc.Charts("Sheet1", "Object 1")

The following example instantiate the Chart service by creating a new chart object based on the data contained in the range "Sheet1.A1:C10".

        Dim oDoc as Object, oChart as Object
        Set oDoc = CreateScriptService("Calc")
        Set oChart = oDoc.CreateChart("My Chart", "Sheet1", "Sheet1.A1:C10")

Read the CreateChart method description to learn more about its arguments.

##### En Python

Los ejemplos anteriores pueden escribirse en Python de esta manera:

        from scriptforge import CreateScriptService
        doc = CreateScriptService("Calc")
        chart = doc.Charts("Sheet1", "Object 1")

        doc = CreateScriptService("Calc")
        chart = doc.CreateChart("My Chart", "Sheet1", "Sheet1.A1:C10")

## Propiedades

Nombre | De solo lectura | Tipo | Descripción
--- | --- | --- | ---
ChartType | No | String | Specifies the chart type as a string that can assume one of the following values: "Pie", "Bar", "Donut", "Column", "Area", "Line", "XY", "Bubble", "Net".
Deep | No | Boolean | When True indicates that the chart is three-dimensional and each series is arranged in the z-direction. When False series are arranged considering only two dimensions.
Dim3D | No | Boolean or String | Specifies if the chart is displayed with 3D elements. If the value is a string, it must be either "Bar", "Cylinder", "Cone" or "Pyramid". If the boolean True value is specified, then the chart is displayed using 3D bars.
Exploded | No | Numeric | Specifies how much pie segments are offset from the chart center as a percentage of the radius. Applicable to pie and donut charts only.
Filled | No | Boolean | When True, specifies a filled net chart. Applicable to net charts only.
Legend | No | Boolean | Specifies whether or not the chart has a legend.
Percent | No | Boolean | When True, chart series are stacked and each category sums up to 100%. Applicable to Area, Bar, Bubble, Column and Net charts.
Stacked | No | Boolean | When True, chart series are stacked. Applicable to Area, Bar, Bubble, Column and Net charts.
Title | No | String | Especifica el título principal del gráfico.
XTitle | No | String | Especifica el título del eje X.
YTitle | No | String | Especifica el título del eje Y.
XChartObj | Sí | Objeto UNO | Returns the object representing the chart, which is an instance of the ScChartObj class.
XDiagram | Sí | Objeto UNO | Returns the com.sun.star.chart.XDiagram object representing the diagram of the chart.
XShape | Sí | Objeto UNO | Returns the com.sun.star.drawing.XShape object representing the shape of the chart.
XTableChart | Sí | Objeto UNO | Returns the com.sun.star.table.XTableChart object representing the data being displayed in the chart.

## Crear un gráfico

Considere los siguientes datos en el intervalo «A1:B6» de una hoja llamada «Informe».

| A | B
--- | --- | ---
1 | Sample A | Sample B
2 | 36 | 40
3 | 39 | 43
4 | 45 | 40
5 | 52 | 48

The examples below in Basic and Python show how to create a line chart from this data with legends.

##### En BASIC

        oDoc = CreateScriptService("Calc")
        oChart = oDoc.CreateChart("Samples", "Report", "Report.A1:B6")
        oChart.ChartType = "Line"
        oChart.Legend = True
        oChart.Resize(1000, 1000, 25000, 15000)

##### En Python

        doc = CreateScriptService("Calc")
        chart = doc.CreateChart("Samples", "Report", "Report.A1:B6")
        chart.ChartType = "Line"
        chart.Legend = True
        chart.Resize(1000, 1000, 25000, 15000)

The chart does not need to be created in the same sheet where the data is located. It can be created in any existing sheet in the current file by specifying the sheet name in the second argument of the CreateChart method.

## Métodos

Lista de métodos en el servicio Chart
ExportToFile | Resize

## ExportToFile

Saves the chart as an image file in a specified location. Returns True if the image file could be successfully created.

### Sintaxis:

chart.ExportToFile(filename: str, imagetype: str = "png", overwrite: bool = False): bool

### Parámetros:

filename: Identifies the path and file name where the image will be saved. It must follow the notation defined in SF_FileSystem.FileNaming.

imagetype: The name of the image type to be created. The following values are accepted: "gif", "jpeg", "png" (default), "svg" and "tiff".

overwrite: Specifies if the destination file can be overwritten (Default = False).

### Ejemplo:

##### En BASIC

          oChart.ExportToFile("C:\Temp\myChart.svg", ImageType := "svg", Overwrite := True)

##### En Python

          chart.ExportToFile(r"C:\Temp\myChart.svg", imagetype="svg", overwrite=True)

## Resize

Changes the position of the chart in the current sheet and modifies its width and height. Returns True if resizing was successful.

### Sintaxis:

chart.Resize([xpos: int], [ypos: int], [width: int], [height: int]): bool

### Parámetros:

xpos, ypos: Specify the new X and Y positions of the chart. If any of these values are omitted or if negative values are provided, the corresponding positions are left unchanged.

width: Specify the new width of the chart. If this argument is omitted or if a negative value is provided, the chart width is left unchanged.

height: Specify the new height of the chart. If this argument is omitted or if a negative value is provided, the chart height is left unchanged.

All arguments are provided as integer values that correspond to 1/100 of a millimeter.

### Ejemplo:

##### En BASIC

          ' Changes only X and Y position
          oChart.Rezise(1000, 3000)
          ' Cambia solo la anchura y la altura del gráfico
          oChart.Resize(, , 25000, 12500)
          ' Keyword arguments are supported
          oChart.Resize(Width := 25000, Height := 12500)

##### En Python

          chart.Rezise(1000, 3000)
          chart.Resize(-1, -1, 20000, 20000)
          chart.Resize(width=25000, height=12500)

Todas las rutinas o identificadores BASIC de ScriptForge precedidas por guion bajo «_» están reservadas para uso interno. No deben utilizarse en macros BASIC o secuencias Python.

Temas relacionados

Servicio SFDocuments.Calc

¡Necesitamos su ayuda!