Angular Superposiciones de gráficos
El Angular IgxDataChartComponent
permite la colocación de líneas horizontales o verticales en un único valor numérico que se define mediante el uso de la función . IgxValueOverlayComponent
Esto puede ayudarle a visualizar datos como la media o la mediana de una serie en particular.
Ejemplo de superposición de valores de Angular
El siguiente ejemplo muestra un Gráfico de columnas con algunas superposiciones de valores horizontales trazadas.
EXAMPLE
DATA
MODULES
TS
HTML
SCSS
import { Injectable } from "@angular/core" ;
@Injectable ()
export class SharedData {
public static getEnergyProduction ( ) {
const data: any [] = [
{
Coal : 400000000 ,
Country : "Canada" ,
Gas : 175000000 ,
Hydro : 350000000 ,
Nuclear : 225000000 ,
Oil : 100000000
},
{
Coal : 925000000 ,
Country : "China" ,
Gas : 350000000 ,
Hydro : 625000000 ,
Nuclear : 400000000 ,
Oil : 200000000
},
{
Coal : 550000000 ,
Country : "Russia" ,
Gas : 250000000 ,
Hydro : 425000000 ,
Nuclear : 475000000 ,
Oil : 200000000
},
{
Coal : 450000000 ,
Country : "Australia" ,
Gas : 150000000 ,
Hydro : 350000000 ,
Nuclear : 175000000 ,
Oil : 100000000
},
{
Coal : 800000000 ,
Country : "United States" ,
Gas : 475000000 ,
Hydro : 750000000 ,
Nuclear : 575000000 ,
Oil : 250000000
},
{
Coal : 375000000 ,
Country : "France" ,
Gas : 350000000 ,
Hydro : 325000000 ,
Nuclear : 275000000 ,
Oil : 150000000
}
];
return data;
}
public static getItems(startValue: number , maxPoints : number , useShortLabels?: boolean ): any [] {
const data: any [] = [];
let value = startValue;
for (let i = 0 ; i <= maxPoints; i++) {
value += Math .random() * 4.0 - 2.0 ;
const v = Math .round(value);
let l = i.toString();
if (useShortLabels) {
l = this .toShortString(i);
}
data.push({ Label : l, Value : v });
}
return data;
}
public static getTemperatures(startValue: number , startYear : number , endYear : number ): any [] {
const data: any [] = [];
let value = startValue;
for (let i = startYear; i <= endYear; i++) {
value += (Math .random() - 0.5 ) * 0.5 ;
const high = value + (Math .random() * 2 );
const low = value - (Math .random() * 2 );
const v = Math .abs(Math .round(value * 10 ) / 10 );
const h = Math .abs(Math .round(high * 10 ) / 10 );
const l = Math .abs(Math .round(low * 10 ) / 10 );
data.push({ Label : i.toString(), Value : v, High : h, Low : l });
}
return data;
}
public static getLastItem(array: any []): any {
if (array.length === 0 ) {
return null ;
}
return array[array.length - 1 ];
}
public static getNewItem(array: any [], index : number ): any {
const lastItem = this .getLastItem(array);
const newValue = lastItem.Value + Math .random() * 4.0 - 2.0 ;
return { Label : index.toString(), Value : newValue };
}
public static toShortString(largeValue: number ): string {
let roundValue: number ;
if (largeValue >= 1000000 ) {
roundValue = Math .round(largeValue / 100000 ) / 10 ;
return roundValue + "m" ;
}
if (largeValue >= 1000 ) {
roundValue = Math .round(largeValue / 100 ) / 10 ;
return roundValue + "k" ;
}
roundValue = Math .round(largeValue);
return roundValue + "" ;
}
public static addDays(date: Date , days : number ): Date {
date.setDate(date.getDate() + days);
return date;
}
}
ts コピー import { NgModule } from "@angular/core" ;
import { FormsModule } from "@angular/forms" ;
import { CommonModule } from "@angular/common" ;
import { BrowserModule } from "@angular/platform-browser" ;
import { BrowserAnimationsModule } from "@angular/platform-browser/animations" ;
import { AppComponent } from "./app.component" ;
import { IgxDataChartCoreModule, IgxDataChartCategoryModule, IgxValueOverlayModule, IgxLegendModule } from "igniteui-angular-charts" ;
import { SharedData } from "./SharedData" ;
@NgModule ({
bootstrap : [AppComponent],
declarations : [
AppComponent,
],
imports : [
BrowserModule,
BrowserAnimationsModule,
CommonModule,
FormsModule,
IgxDataChartCoreModule,
IgxDataChartCategoryModule,
IgxValueOverlayModule,
IgxLegendModule
],
providers : [SharedData],
schemas : []
})
export class AppModule {}
ts コピー import { Component, OnInit } from "@angular/core" ;
@Component ({
standalone : false ,
selector : "app-root" ,
styleUrls : ["./app.component.scss" ],
templateUrl : "./app.component.html"
})
export class AppComponent {
public data: any [];
constructor ( ) {
this .initData();
}
public initData ( ) {
this .data = [
{ Label : 1 , Value : 1.0 },
{ Label : 2 , Value : 2.0 },
{ Label : 3 , Value : 6.0 },
{ Label : 4 , Value : 8.0 },
{ Label : 5 , Value : 2.0 },
{ Label : 6 , Value : 6.0 },
{ Label : 7 , Value : 4.0 },
{ Label : 8 , Value : 2.0 },
{ Label : 9 , Value : 1.0 }
];
}
}
ts コピー <div class ="container vertical" >
<igx-legend #legend orientation ="horizontal" > </igx-legend >
<igx-data-chart #chart height ="100%" width ="100%" [dataSource ]="data" >
<igx-category-x-axis #xAxis label ="Label" > </igx-category-x-axis >
<igx-numeric-y-axis #yAxis minimumValue =0 maximumValue =10 > </igx-numeric-y-axis >
<igx-column-series [xAxis ]="xAxis" [yAxis ]="yAxis" valueMemberPath ="Value" showDefaultTooltip =true
markerType ="None" > </igx-column-series >
<igx-value-overlay [axis ]="yAxis" value =2.0 thickness =5 > </igx-value-overlay >
<igx-value-overlay [axis ]="yAxis" value =3.6 thickness =5 > </igx-value-overlay >
<igx-value-overlay [axis ]="yAxis" value =5.8 thickness =5 > </igx-value-overlay >
<igx-value-overlay [axis ]="yAxis" value =1.0 thickness =5 > </igx-value-overlay >
<igx-value-overlay [axis ]="yAxis" value =8.0 thickness =5 > </igx-value-overlay >
<igx-value-overlay [axis ]="yAxis" value =7.0 thickness =5 > </igx-value-overlay >
<igx-value-overlay [axis ]="yAxis" value =5.0 thickness =5 > </igx-value-overlay >
</igx-data-chart >
</div >
html コピー
¿Te gusta esta muestra? Obtenga acceso a nuestro kit de herramientas de Ignite UI for Angular completo y comience a crear sus propias aplicaciones en minutos. Descárgalo gratis.
Angular Propiedades de superposición de valores
A diferencia de otros tipos de series que utilizan ItemsSource
para el enlace de datos, la superposición de valores utiliza una propiedad ValueMemberPath
para enlazar un único valor numérico. Además, la superposición de valores requiere que usted defina un único axis
para usar. Si usa un eje X, la superposición de valores será una línea vertical, y si usa un eje Y, será una línea horizontal.
Cuando se utiliza un eje numérico X o Y, la propiedad ValueMemberPath
debe reflejar el valor numérico real en el eje donde desea que se dibuje la superposición de valores. Cuando se utiliza un eje de categoría X o Y, ValueMemberPath
debe reflejar el índice de la categoría en la que desea que aparezca la superposición de valores.
Cuando se utiliza la superposición de valores con un eje de ángulo numérico, aparecerá como una línea desde el centro del gráfico y cuando se utiliza un eje de radio numérico, aparecerá como un círculo.
Las propiedades de apariencia IgxValueOverlayComponent
se heredan de IgxSeriesComponent
, por lo que brush
y thickness
, por ejemplo, están disponibles y funcionan de la misma manera que con otros tipos de series.
También es posible mostrar una anotación de eje en un IgxValueOverlayComponent
para mostrar el valor de la superposición en el eje propietario. Para mostrar esto, puede establecer la propiedad isAxisAnnotationEnabled
en verdadero.
Angular Capa de valor
Los componentes de gráficos de Angular también exponen la capacidad de usar líneas de valor para llamar a diferentes puntos focales de los datos, como los valores mínimo, máximo y promedio.
La aplicación de IgxValueLayerComponent
en los componentes IgxCategoryChartComponent
e IgxFinancialChartComponent
se realiza estableciendo la propiedad valueLines
en el gráfico. Esta propiedad toma una colección de la enumeración ValueLayerValueMode
. Puede mezclar y combinar varias capas de valores en el mismo gráfico agregando varias enumeraciones ValueLayerValueMode
a la colección valueLines
del gráfico.
En IgxDataChartComponent
, esto se hace agregando un IgxValueLayerComponent
a la colección IgxSeriesComponent
del gráfico y luego estableciendo la propiedad ValueMode
en una de las enumeraciones ValueLayerValueMode
. Cada una de estas enumeraciones y lo que significan se enumeran a continuación:
Auto
: el modo de valor predeterminado de la enumeración ValueLayerValueMode
.
Average
: aplica líneas de valor potencialmente múltiples para indicar el valor promedio de cada serie trazada en el gráfico.
GlobalAverage
: aplica una línea de valor único para mostrar el promedio de todos los valores de la serie en el gráfico.
GlobalMaximum
: aplica una línea de valor único para indicar el valor máximo absoluto de todos los valores de la serie en el gráfico.
GlobalMinimum
: aplica una línea de valor único para indicar el valor mínimo absoluto de todos los valores de la serie en el gráfico.
Maximum
: aplica líneas de valor potencialmente múltiples para indicar el valor máximo de cada serie trazada en el gráfico.
Minimum
: aplica líneas de valor potencialmente múltiples para indicar el valor mínimo de cada serie trazada en el gráfico.
Si desea evitar que se tenga en cuenta una serie en particular al utilizar el elemento IgxValueLayerComponent
, puede establecer la propiedad targetSeries
en la capa. Esto obligará a la capa a apuntar a la serie que usted defina. Puede tener tantos elementos IgxValueLayerComponent
dentro de un único IgxDataChartComponent
como desee.
El siguiente ejemplo demuestra el uso de diferentes valueLines
en IgxCategoryChartComponent
:
EXAMPLE
DATA
MODULES
TS
HTML
SCSS
export class CountryRenewableElectricityItem {
public constructor (init: Partial<CountryRenewableElectricityItem> ) {
Object .assign(this , init);
}
public year: string ;
public europe: number ;
public china: number ;
public america: number ;
}
export class CountryRenewableElectricity extends Array <CountryRenewableElectricityItem > {
public constructor (items: Array <CountryRenewableElectricityItem> | number = -1 ) {
if (Array .isArray(items)) {
super (...items);
} else {
const newItems = [
new CountryRenewableElectricityItem(
{
year : `2009` ,
europe : 34 ,
china : 21 ,
america : 19
}),
new CountryRenewableElectricityItem(
{
year : `2010` ,
europe : 43 ,
china : 26 ,
america : 24
}),
new CountryRenewableElectricityItem(
{
year : `2011` ,
europe : 66 ,
china : 29 ,
america : 28
}),
new CountryRenewableElectricityItem(
{
year : `2012` ,
europe : 69 ,
china : 32 ,
america : 26
}),
new CountryRenewableElectricityItem(
{
year : `2013` ,
europe : 58 ,
china : 47 ,
america : 38
}),
new CountryRenewableElectricityItem(
{
year : `2014` ,
europe : 40 ,
china : 46 ,
america : 31
}),
new CountryRenewableElectricityItem(
{
year : `2015` ,
europe : 78 ,
china : 50 ,
america : 19
}),
new CountryRenewableElectricityItem(
{
year : `2016` ,
europe : 13 ,
china : 90 ,
america : 52
}),
new CountryRenewableElectricityItem(
{
year : `2017` ,
europe : 78 ,
china : 132 ,
america : 50
}),
new CountryRenewableElectricityItem(
{
year : `2018` ,
europe : 40 ,
china : 134 ,
america : 34
}),
new CountryRenewableElectricityItem(
{
year : `2018` ,
europe : 40 ,
china : 134 ,
america : 34
}),
new CountryRenewableElectricityItem(
{
year : `2019` ,
europe : 80 ,
china : 96 ,
america : 38
}),
];
super (...newItems.slice(0 ));
}
}
}
ts コピー import { NgModule } from "@angular/core" ;
import { FormsModule } from "@angular/forms" ;
import { CommonModule } from "@angular/common" ;
import { BrowserModule } from "@angular/platform-browser" ;
import { BrowserAnimationsModule } from "@angular/platform-browser/animations" ;
import { AppComponent } from "./app.component" ;
import { IgxPropertyEditorPanelModule } from 'igniteui-angular-layouts' ;
import { IgxLegendModule, IgxCategoryChartModule } from 'igniteui-angular-charts' ;
@NgModule ({
bootstrap : [AppComponent],
declarations : [
AppComponent
],
imports : [
BrowserModule,
BrowserAnimationsModule,
CommonModule,
FormsModule,
IgxPropertyEditorPanelModule,
IgxLegendModule,
IgxCategoryChartModule
],
providers : [],
schemas : []
})
export class AppModule {}
ts コピー import { AfterViewInit, Component, ViewChild, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core' ;
import { ComponentRenderer, PropertyEditorPanelDescriptionModule, LegendDescriptionModule, CategoryChartDescriptionModule } from 'igniteui-angular-core' ;
import { CountryRenewableElectricityItem, CountryRenewableElectricity } from './CountryRenewableElectricity' ;
import { IgxPropertyEditorPropertyDescriptionChangedEventArgs, IgxPropertyEditorPropertyDescriptionComponent } from 'igniteui-angular-layouts' ;
import { IgxCategoryChartComponent, MarkerType, MarkerType_$type } from 'igniteui-angular-charts' ;
import { EnumUtil } from 'igniteui-angular-core' ;
import { IgxLegendComponent } from 'igniteui-angular-charts' ;
import { IgxPropertyEditorPanelComponent } from 'igniteui-angular-layouts' ;
import { defineAllComponents } from 'igniteui-webcomponents' ;
defineAllComponents();
@Component ({
standalone : false ,
selector : "app-root" ,
styleUrls : ["./app.component.scss" ],
templateUrl : "./app.component.html" ,
changeDetection : ChangeDetectionStrategy.OnPush
})
export class AppComponent implements AfterViewInit
{
@ViewChild ("legend" , { static : true } )
private legend: IgxLegendComponent
@ViewChild ("propertyEditor" , { static : true } )
private propertyEditor: IgxPropertyEditorPanelComponent
@ViewChild ("valueListEditor" , { static : true } )
private valueListEditor: IgxPropertyEditorPropertyDescriptionComponent
@ViewChild ("chart" , { static : true } )
private chart: IgxCategoryChartComponent
private _countryRenewableElectricity: CountryRenewableElectricity = null ;
public get countryRenewableElectricity (): CountryRenewableElectricity {
if (this ._countryRenewableElectricity == null )
{
this ._countryRenewableElectricity = new CountryRenewableElectricity();
}
return this ._countryRenewableElectricity;
}
private _componentRenderer: ComponentRenderer = null ;
public get renderer (): ComponentRenderer {
if (this ._componentRenderer == null ) {
this ._componentRenderer = new ComponentRenderer();
var context = this ._componentRenderer.context;
PropertyEditorPanelDescriptionModule.register(context);
LegendDescriptionModule.register(context);
CategoryChartDescriptionModule.register(context);
}
return this ._componentRenderer;
}
public constructor (private _detector: ChangeDetectorRef )
{
}
public ngAfterViewInit(): void
{
}
public editorChangeUpdateValueLines({ sender, args }: { sender : any , args : IgxPropertyEditorPropertyDescriptionChangedEventArgs }): void {
var item = sender as IgxPropertyEditorPropertyDescriptionComponent;
var chart = this .chart;
var valueLineType = item.primitiveValue;
chart.valueLines = valueLineType;
}
}
ts コピー <div class ="container vertical sample" >
<div class ="options vertical" >
<igx-property-editor-panel
name ="PropertyEditor"
#propertyEditor
[componentRenderer ]="renderer"
[target ]="chart"
descriptionType ="CategoryChart"
isHorizontal ="true"
isWrappingEnabled ="true" >
<igx-property-editor-property-description
propertyPath ="ValueListHandler"
name ="ValueListEditor"
#valueListEditor
label ="Value List"
shouldOverrideDefaultEditor ="true"
valueType ="EnumValue"
dropDownValues ="Auto, Average, GlobalAverage, GlobalMaximum, GlobalMinimum, Maximum, Minimum"
dropDownNames ="Auto, Average, GlobalAverage, GlobalMaximum, GlobalMinimum, Maximum, Minimum"
primitiveValue ="Auto"
(changed )="this.editorChangeUpdateValueLines($event)" >
</igx-property-editor-property-description >
</igx-property-editor-panel >
</div >
<div class ="legend-title" >
Renewable Electricity Generated
</div >
<div class ="legend" >
<igx-legend
name ="legend"
#legend
orientation ="Horizontal" >
</igx-legend >
</div >
<div class ="container fill" >
<igx-category-chart
name ="chart"
#chart
[dataSource ]="countryRenewableElectricity"
includedProperties ="year, america, europe"
chartType ="Column"
[legend ]="legend"
isHorizontalZoomEnabled ="false"
isVerticalZoomEnabled ="false"
crosshairsDisplayMode ="None"
isTransitionInEnabled ="false"
yAxisMinimumValue ="0"
yAxisMaximumValue ="100" >
</igx-category-chart >
</div >
</div >
html コピー
Angular Superposiciones financieras
También puede trazar superposiciones financieras e indicadores incorporados en Angular gráfico de acciones .
Recursos adicionales
Puede encontrar más información sobre tipos de gráficos relacionados en estos temas:
Referencias de API
La siguiente es una lista de miembros de API mencionados en las secciones anteriores: