AstrolUI AstrolUI
Amarillo Naranja Rojo Verde Azul Morado Color propio
Modo claro
AstrolChart

AstrolChart<TItem> es el contenedor de la gráfica y dentro se colocan una o varias series. Cada serie recibe una lista de objetos de su aplicación (Items) y unas funciones que dicen qué valor va en cada eje. No hay que preparar arrays ni JSON: se trabaja con sus propias clases y LINQ.

1. Ejemplo mínimo

Sales by month25025000JanJanFebFebMarMarAprApr
Download SVG
Download PNG
Download CSV
@using AstrolCharts
 
@* 1. A chart (AstrolChart) with the type of your data (TItem).
 2. One or more series: which items (Items), what goes on X (XValue) and on Y (YValue).
 3. SeriesType chooses how it is drawn: Bar, Line, Area, Pie, Donut... *@
<AstrolChart TItem="Sale" Title="Sales by month">
 <AstrolPointSeries TItem="Sale"
 Items="sales"
 Name="Sales"
 SeriesType="SeriesType.Bar"
 XValue="e => e.Month"
 YValue="e => e.Amount" />
</AstrolChart>
 
@code {
 private readonly List<Sale> sales = new()
 {
 new() { Month = "Jan", Amount = 120 },
 new() { Month = "Feb", Amount = 180 },
 new() { Month = "Mar", Amount = 150 },
 new() { Month = "Apr", Amount = 210 },
 };
 
 public class Sale
 {
 public string Month { get; set; } = string.Empty;
 public decimal Amount { get; set; }
 }
}

2. Cómo se conectan los datos

  • TItem: la clase de sus datos. Va en la gráfica y en cada serie (TItem="Sale").
  • Items: la lista de objetos de la serie. Para varias series de una misma lista, filtre con LINQ: Items="sales.Where(s => s.Year == 2026)".
  • XValue: lo que va en el eje X (categoría, número o fecha). Los objetos con el mismo X forman un solo punto.
  • YValue: el valor Y de cada objeto, cuando hay un objeto por punto.
  • YAggregate: cuando hay varios objetos por punto, cómo se combinan: e => e.Sum(x => x.Amount), Average, Count(), Max...
  • OrderBy / OrderByDescending: orden de los puntos, p. ej. OrderByDescending="p => p.Y" para un ranking.
  • Name: nombre de la serie (leyenda y tooltip). Color fija su color; PointColor da un color por punto.
  • ShowDataLabels: muestra el valor sobre cada punto o barra.
  • Group: en barras apiladas, las series con el mismo Group forman una misma pila.
  • DataPointMutator: modifica cada punto antes de pintarlo (color, texto extra...).
  • Fechas: ponga XAxisType="XAxisType.Datetime" en la gráfica y pase la fecha como milisegundos Unix: XValue="e => e.Date.ToUnixTimeMilliseconds()".
  • Ejes numéricos (dispersión): XAxisType="XAxisType.Numeric" y un XValue numérico.
  • Si cambia el contenido de la lista (sin crear otra), llame a UpdateSeriesAsync() mediante @ref; si asigna una lista nueva, la gráfica se actualiza sola.

3. Tipos de series

  • AstrolPointSeries: un valor por punto (YValue o YAggregate). Su SeriesType elige el dibujo: Line, Area, Bar (columnas; horizontales con PlotOptions.Bar.Horizontal), Pie, Donut, PolarArea, RadialBar, Radar, Scatter, Heatmap y Treemap. Se pueden combinar tipos en una misma gráfica (columnas + línea).
  • AstrolRangeSeries: barras de un inicio a un fin (YMinValue, YMaxValue): diagramas de Gantt y líneas de tiempo.
  • AstrolRangeAreaSeries: banda entre Bottom y Top (mínimo y máximo).
  • AstrolCandleSeries: velas japonesas con Open, High, Low y Close.
  • AstrolBoxPlotSeries: diagramas de caja con Min, Quantile1, Median, Quantile3 y Max.
  • AstrolBubbleSeries: burbujas con YAggregate (posición) y ZAggregate (tamaño).
  • AstrolGauge: indicador de un solo porcentaje sin definir series: Title, Label, Percentage (0-100) y Options.
  • Todas las series comparten Items, Name, XValue, Color, PointColor, ShowDataLabels, Stroke (SeriesStroke: Color, Width, DashSpace) y Group.

4. Opciones (AstrolChartOptions)

Todo el aspecto se configura con Options (AstrolChartOptions<TItem>). Sus propiedades siguen exactamente la documentación de opciones de ApexCharts con nombres de C#: Chart (apilado, zoom, barra de herramientas, animaciones), Colors, Stroke (grosor y curva), Fill, Markers, DataLabels, Legend, Tooltip, Xaxis, Yaxis (varios ejes), Grid, PlotOptions (por tipo: Bar, Pie, RadialBar, Heatmap, Treemap...), Annotations, Theme y Responsive. Cree las opciones una vez (un campo) y no en cada render.

private readonly AstrolChartOptions<Sale> options = new()
{
 Chart = new Chart { Stacked = true, Toolbar = new Toolbar { Show = false } },
 Colors = new List<string> { "#ffd800", "#007bff" },
 Stroke = new Stroke { Curve = Curve.Smooth, Width = 3 },
 DataLabels = new DataLabels { Enabled = true },
 Legend = new Legend { Position = LegendPosition.Bottom },
 PlotOptions = new PlotOptions { Bar = new PlotOptionsBar { Horizontal = true, BorderRadius = 4 } },
 Xaxis = new XAxis { Title = new AxisTitle { Text = "Month" } },
 Yaxis = new List<YAxis> { new YAxis { Title = new AxisTitle { Text = "Amount" } } },
 Tooltip = new Tooltip { Shared = true, Intersect = false },
};
 
// <AstrolChart TItem="Sale" Options="options"> ... </AstrolChart>

5. Tema, colores y rendimiento

  • Los textos, ejes y tooltips siguen el modo claro/oscuro de AstrolUI automáticamente.
  • Colores: Options.Colors (lista, uno por serie o por porción), Color en cada serie, PointColor por punto o una paleta de ApexCharts con Options.Theme = new Theme { Palette = PaletteType.Palette3 }.
  • Tamaño: por defecto ocupa el ancho del contenedor; el alto se fija con Height (p. ej. Height="@(300)" o Height="@("50vh")").
  • ApexCharts se descarga una sola vez y solo en las páginas con gráficas. Con muchos puntos, agregue los datos (YAggregate o en el servidor) en lugar de enviar miles de objetos.
  • FormatXAxisLabel y FormatYAxisLabel (funciones de C# para las etiquetas) solo funcionan en Blazor WebAssembly; en Blazor Server use Options.Xaxis.Labels.Formatter (función JavaScript en texto).

Parámetros que admite

AstrolChart<TItem>:

  • TItem (T), clase de los datos (requerido).
  • ChildContent (RenderFragment), las series. Si usa AstrolPointTooltip, ponga las series dentro de <ChildContent>.
  • Title (string), título de la gráfica.
  • Options (AstrolChartOptions<TItem>), aspecto y comportamiento (ver sección 4).
  • XAxisType (XAxisType?), tipo del eje X: Category, Datetime o Numeric.
  • Width / Height (object), tamaño (número en px o texto CSS).
  • AstrolPointTooltip (RenderFragment<HoverData<TItem>>), tooltip con contenido Blazor; context.DataPoint.Items son los objetos del punto.
  • FormatXAxisLabel / FormatYAxisLabel (Func<decimal, string>), etiquetas de los ejes con C# (solo WebAssembly).
  • GroupPoints (GroupPoints), agrupa los puntos pequeños en uno ("Otros"): MaxCount, MinCount, PercentageThreshold, Name.
  • Debug (bool), escribe en la consola las llamadas a ApexCharts.
  • Eventos de datos: OnDataPointSelection, OnMarkerClick, OnClick (SelectedData<TItem>: Series, DataPoint, IsSelected, índices), OnDataPointEnter / OnDataPointLeave (HoverData<TItem>), OnLegendClicked, OnXAxisLabelClick, OnMouseMove, OnMouseLeave.
  • Eventos de zoom y selección: OnZoomed, OnSelection, OnBrushScrolled, OnScrolled, OnBeforeZoom, OnBeforeResetZoom.
  • Eventos de ciclo de vida: OnBeforeMount, OnMounted, OnRendered, OnUpdated, OnAnimationEnd.
  • Eventos de anotaciones: OnAnnotationLabelClick, OnAnnotationLabelMouseEnter/Leave, OnAnnotationPointClick, OnAnnotationPointMouseEnter/Leave.

Métodos públicos

Con @ref (private AstrolChart<Sale>? chart;):

  • UpdateSeriesAsync(animate): vuelve a leer las series (tras cambiar los datos).
  • UpdateOptionsAsync(redrawPaths, animate, updateSyncedCharts): aplica cambios en Options.
  • RenderAsync(): vuelve a crear la gráfica completa.
  • AppendDataAsync(items): añade puntos al final (datos en tiempo real).
  • ToggleSeriesAsync / ShowSeriesAsync / HideSeriesAsync(nombre): muestra u oculta una serie.
  • ToggleDataPointSelectionAsync(serie, punto): selecciona un punto desde código.
  • ZoomXAsync(inicio, fin) y ResetSeriesAsync(actualizar, quitarZoom).
  • AddPointAnnotationAsync, AddXAxisAnnotationAsync, AddYAxisAnnotationAsync, RemoveAnnotationAsync(id), ClearAnnotationsAsync().
  • GetDataUriAsync(new DataUriOptions { Scale, Width }): imagen PNG de la gráfica (data URI).
  • SetLocaleAsync(nombre): cambia el idioma de la gráfica (definido en Options.Chart.Locales).
Markdown para IA © 2026 AstrolUI v10.0.13