# Gráficos

- Human documentation: [https://docs.univer.ai/es-ES/guides/sheets/features/charts](https://docs.univer.ai/es-ES/guides/sheets/features/charts)

- Agent Markdown: [https://docs.univer.ai/es-ES/guides/sheets/features/charts.md](https://docs.univer.ai/es-ES/guides/sheets/features/charts.md)

- Requested language: `es-ES`

- Content language: `es-ES`

- Documentation version: `1.2.0`

- Source: [sheets/features/charts.es-ES.mdx](https://github.com/dream-num/documentation/blob/dev/content/guides/sheets/features/charts.es-ES.mdx)

---

#### Package metadata

```json
{
  "mobile": true,
  "preset": [
    {
      "client": "@univerjs/preset-sheets-advanced",
      "locale": "@univerjs/preset-sheets-advanced/locales/es-ES",
      "style": "@univerjs/preset-sheets-advanced/lib/index.css"
    }
  ],
  "plugins": [
    {
      "client": "@univerjs-pro/chart-ui",
      "locale": "@univerjs-pro/chart-ui/locale/es-ES",
      "style": "@univerjs-pro/chart-ui/lib/index.css"
    },
    {
      "client": "@univerjs-pro/sheets-chart",
      "locale": "@univerjs-pro/sheets-chart/locale/es-ES",
      "facade": "@univerjs-pro/sheets-chart/facade"
    },
    {
      "client": "@univerjs-pro/sheets-chart-ui",
      "locale": "@univerjs-pro/sheets-chart-ui/locale/es-ES",
      "style": "@univerjs-pro/sheets-chart-ui/lib/index.css"
    }
  ],
  "license": true,
  "server": false
}
```

Los gráficos visualizan los datos de la hoja de trabajo con el modelo de gráfico y los paquetes de UI.

> Interactive example: [Open the playground](/playground/sheets/charts)

## Modo de complemento

#### npm

```bash
npm install @univerjs-pro/chart-ui @univerjs-pro/sheets-chart @univerjs-pro/sheets-chart-ui
```

#### pnpm

```bash
pnpm add @univerjs-pro/chart-ui @univerjs-pro/sheets-chart @univerjs-pro/sheets-chart-ui
```

#### yarn

```bash
yarn add @univerjs-pro/chart-ui @univerjs-pro/sheets-chart @univerjs-pro/sheets-chart-ui
```

#### bun

```bash
bun add @univerjs-pro/chart-ui @univerjs-pro/sheets-chart @univerjs-pro/sheets-chart-ui
```

```ts
import ChartUIEsES from '@univerjs-pro/chart-ui/locale/es-ES'
import { UniverSheetsChartPlugin } from '@univerjs-pro/sheets-chart'
import { UniverSheetsChartUIPlugin } from '@univerjs-pro/sheets-chart-ui'
import SheetsChartUIEsES from '@univerjs-pro/sheets-chart-ui/locale/es-ES'
import SheetsChartEsES from '@univerjs-pro/sheets-chart/locale/es-ES'
import { LocaleType, mergeLocales, Univer } from '@univerjs/core'
import '@univerjs-pro/chart-ui/facade'
import '@univerjs-pro/sheets-chart/facade'
import '@univerjs-pro/chart-ui/lib/index.css'
import '@univerjs-pro/sheets-chart-ui/lib/index.css'

const univer = new Univer({
  locale: LocaleType.ES_ES,
  locales: {
    [LocaleType.ES_ES]: mergeLocales(ChartUIEsES, SheetsChartEsES, SheetsChartUIEsES),
  },
})

univer.registerPlugin(UniverSheetsChartPlugin)
univer.registerPlugin(UniverSheetsChartUIPlugin)
```

## Compatibilidad móvil

Configure primero el [editor móvil](https://docs.univer.ai/es-ES/guides/sheets/getting-started/installation.md#mobile-support). En la inicialización en modo plugin de esta página, sustituya los registros de escritorio siguientes por las exportaciones móviles de los mismos paquetes **antes de abrir un documento**. Conserve modelos, estilos, traducciones e importaciones Facade; no registre ambas variantes.

| Paquete                         | Registro de escritorio      | Registro móvil                    |
| ------------------------------- | --------------------------- | --------------------------------- |
| `@univerjs-pro/sheets-chart-ui` | `UniverSheetsChartUIPlugin` | `UniverSheetsChartMobileUIPlugin` |

## Modo preestablecido

La función de gráficos está incluida en `@univerjs/preset-sheets-advanced` y requiere el preset de dibujo en tiempo de ejecución.

#### npm

```bash
npm install @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

#### pnpm

```bash
pnpm add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

#### yarn

```bash
yarn add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

#### bun

```bash
bun add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

```ts
import { UniverSheetsAdvancedPreset } from '@univerjs/preset-sheets-advanced'
import UniverPresetSheetsAdvancedEsES from '@univerjs/preset-sheets-advanced/locales/es-ES'
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'
import UniverPresetSheetsCoreEsES from '@univerjs/preset-sheets-core/locales/es-ES'
import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing'
import UniverPresetSheetsDrawingEsES from '@univerjs/preset-sheets-drawing/locales/es-ES'
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'
import '@univerjs/preset-sheets-advanced/lib/index.css'
import '@univerjs/preset-sheets-core/lib/index.css'
import '@univerjs/preset-sheets-drawing/lib/index.css'

const { univerAPI } = createUniver({
  locale: LocaleType.ES_ES,
  locales: {
    [LocaleType.ES_ES]: mergeLocales(
      UniverPresetSheetsCoreEsES,
      UniverPresetSheetsDrawingEsES,
      UniverPresetSheetsAdvancedEsES,
    ),
  },
  presets: [UniverSheetsCorePreset(), UniverSheetsDrawingPreset(), UniverSheetsAdvancedPreset()],
})
```

## Crear y actualizar gráficos

`worksheet.newChart(type)` crea un constructor independiente. El gráfico no se añade a la hoja hasta que se pasa el resultado de `build()` a `worksheet.insertChart(info)`.

```ts
const workbook = univerAPI.getActiveWorkbook()
if (!workbook) throw new Error('No active workbook')

const worksheet = workbook.getActiveSheet()
const info = worksheet
  .newChart(univerAPI.Enum.ChartTypeString.Column)
  .setSource({
    range: 'A1:D6',
    orientation: univerAPI.Enum.ChartSourceOrientation.Columns,
  })
  .setPosition('F2')
  .setSize(640, 360)
  .setCategoryField(0)
  .setValueFields([1, 2, 3])
  .setTitle('Quarterly revenue')
  .build()

const chart = await worksheet.insertChart(info)
chart.setLegend({ visible: true }).bringToFront()

const updatedInfo = chart.toBuilder(univerAPI.Enum.ChartTypeString.Line).setSubtitle('FY 2026').build()
await chart.update(updatedInfo)

const svg = await chart.exportImage({ format: 'svg' })
```

Los métodos de configuración del `chart` insertado se aplican de inmediato. Use `toBuilder(type)` con `update(info)` cuando necesite una copia completa independiente o cambiar el tipo. `exportImage()` devuelve `undefined` si no hay un renderizador de UI capaz de generar la imagen.

Use `worksheet.getCharts()` y `worksheet.getChart(id)` para obtener gráficos activos. Llame a `await chart.remove()` para eliminar uno y registre temas de ECharts compartidos con `univerAPI.registerTheme(name, theme)`.

## Ejes de categorías multinivel

Cuando varias columnas de origen contiguas forman una jerarquía, pase sus índices, comenzando en cero y en orden de raíz a hoja, a `setCategoryFields()` y active el eje multinivel.

```ts
const info = worksheet
  .newChart(univerAPI.Enum.ChartTypeString.Column)
  .setSource({
    range: 'A1:D7',
    orientation: univerAPI.Enum.ChartSourceOrientation.Columns,
  })
  .setCategoryFields([0, 1])
  .setMultiLevelCategoryAxis(true)
  .setValueFields([2, 3])
  .setPosition('F2')
  .build()

const chart = await worksheet.insertChart(info)
chart.setCategoryFields([0, 1]).setMultiLevelCategoryAxis(true)
```

Llame a `clearCategoryFields()` para eliminar la asignación ordenada. `setMultiLevelCategoryAxis(false)` conserva los campos seleccionados y solo desactiva la representación jerárquica.

## Tipos de gráficos admitidos

Utilice `univerAPI.Enum.ChartTypeString` para `Line`, `Column`, `ColumnStacked`, `ColumnPercentStacked`, `Bar`, `BarStacked`, `BarPercentStacked`, `Pie`, `Donut`, `Area`, `AreaStacked`, `AreaPercentStacked`, `Radar`, `Scatter`, `Combination`, `WordCloud`, `Funnel`, `Bubble`, `Relation`, `Waterfall`, `Pareto`, `Sankey`, `Heatmap`, `Boxplot`, `Candlestick`, `Histogram`, `Treemap`, `Sunburst`, `Gauge` y `Chord`.

Consulte la [Referencia de Chart Facade](https://docs.univer.ai/es-ES/reference/facade/chart.md) para conocer la API de configuración del constructor compartido.

## Datos ocultos y categorías independientes

`setPlotVisibleOnly(false)` incluye valores de filas y columnas ocultas; `getPlotVisibleOnly()` lee el ajuste. `setSeriesToCategory()` asigna índices de campos de valores a índices de categorías. Se refieren a los vectores originales, sin renumerarse al filtrar series visibles. Las entradas omitidas heredan las categorías comunes; `{}` elimina las sustituciones.

Con datos en A:D, la serie D puede usar C como categoría mientras B conserva la categoría común A.

```ts
const chart = worksheet.getCharts()[0]
if (!chart) throw new Error('No chart')
chart.setPlotVisibleOnly(false)
chart.setSeriesToCategory({ 3: [2] })
```

Para informes agregados, consulta los [gráficos dinámicos](https://docs.univer.ai/es-ES/guides/sheets/features/pivot-chart.md).

## Gráficos 3D

Las variantes 3D usan los mismos plugins de gráficos. Seleccione un tipo 3D y configure la vista con su constructor independiente.

Tipos disponibles: `Line3D`, `Column3D`, `ColumnStacked3D`, `ColumnPercentStacked3D`, `Bar3D`, `BarStacked3D`, `BarPercentStacked3D`, `Pie3D`, `Area3D`, `AreaStacked3D` y `AreaPercentStacked3D`.

```ts
const info = worksheet
  .newChart(univerAPI.Enum.ChartTypeString.Column3D)
  .setSource('A1:C5')
  .setCategoryField(0)
  .setValueFields([1, 2])
  .setPosition('F18')
  .setSize(640, 360)
  .setThreeD({
    view: { rotX: 20, rotY: 30, rightAngleAxes: false, perspective: 30 },
    gapDepth: 120,
  })
  .build()

await worksheet.insertChart(info)
```

`perspective` se aplica a los gráficos con ejes cuando `rightAngleAxes` es `false`. `clearThreeD()` borra la vista personalizada, conservando el tipo 3D y el eje de profundidad; use `clearDepthAxis()` para este último. Los gráficos 3D con ejes no ofrecen ejes secundarios ni líneas de tendencia, y `Pie3D` es un gráfico circular sin agujero.

## Ejes de valores logarítmicos

Los ejes numéricos de los gráficos 2D de líneas, áreas, columnas, barras y combinados admiten `scaleType: 'log'`. Use `setYAxis()` para ejes verticales y `setXAxis()` para el eje numérico horizontal de un gráfico de barras. `setRightYAxis()` configura un eje secundario existente.

La base predeterminada es `10`. `logBase` debe ser finito y estar entre `2` y `1000`, incluidos valores fraccionarios como `2.5`. Los límites deben ser positivos. Los puntos con cero o valores negativos se omiten del gráfico sin cambiar los datos. Los gráficos apilados al 100 % y 3D no admiten ejes logarítmicos.

```ts
const info = worksheet
  .newChart(univerAPI.Enum.ChartTypeString.Line)
  .setSource('A1:B5')
  .setYAxis({ scaleType: 'log', logBase: 10 })
  .setPosition('F36')
  .setSize(640, 360)
  .build()

const chart = await worksheet.insertChart(info)

await chart.update(
  chart.toBuilder(univerAPI.Enum.ChartTypeString.Line)
    .setYAxis({ scaleType: 'linear' })
    .build(),
)
```

Construya e inserte un gráfico nuevo, o aplique los cambios con `await chart.update(builder.build())`. `scaleType: 'linear'` elimina la base; otros cambios del eje conservan la escala.
