React 차트 탐색
Ignite UI for React 하면 마우스, 키보드, 터치를 사용하여 대화형 팬 및 확대/축소가 가능합니다.
React Chart Navigation Example
다음 예에서는 사용 가능한 모든 이동 및 확대/축소 옵션을 보여줍니다. 버튼을 사용하여 예제와 상호 작용하거나 드롭다운 또는 확인란을 사용하여 원하는 옵션을 선택할 수 있습니다.
export class SampleFinancialData {
public static create(items?: number ): any [] {
let v = 10000 ;
let o = 500 ;
let h = Math .round(o + (Math .random() * 5 ));
let l = Math .round(o - (Math .random() * 5 ));
let c = Math .round(l + (Math .random() * (h - l)));
if (items === undefined ) {
items = 200 ;
}
const today = new Date ();
const end = new Date (today.getFullYear(), 11 , 1 );
let time = this .addDays(end, -items);
const data: any [] = [];
for (let i = 0 ; i < items; i++) {
const date = time.toDateString();
const label = this .getShortDate(time, false );
data.push({"Time" : time, "Date" : date, "Label" : label, "Close" : c, "Open" : o, "High" : h, "Low" : l, "Volume" : v});
const mod = Math .random() - 0.45 ;
o = Math .round(o + (mod * 5 * 2 ));
v = Math .round(v + (mod * 5 * 100 ));
h = Math .round(o + (Math .random() * 5 ));
l = Math .round(o - (Math .random() * 5 ));
c = Math .round(l + (Math .random() * (h - l)));
time = this .addDays(time, 1 );
}
return data;
}
public static addDays(dt: Date , days : number ): Date {
return new Date (dt.getTime() + days * 24 * 60 * 60 * 1000 );
}
public static getShortDate(dt: Date , showYear : boolean ): string {
const months = [
"Jan" , "Feb" , "Mar" , "Apr" , "May" , "Jun" , "Jul" , "Aug" , "Sep" , "Oct" , "Nov" , "Dec"
];
const ind = dt.getMonth();
const day = dt.getDay() + 1 ;
let label = months[ind] + " " + day;
if (showYear) {
label += " " + dt.getFullYear();
}
return label;
}
}
ts コピー import React from 'react' ;
import ReactDOM from 'react-dom/client' ;
import './index.css' ;
import { IgrDataChart } from "@infragistics/igniteui-react-charts" ;
import { IgrDataChartCoreModule } from "@infragistics/igniteui-react-charts" ;
import { IgrDataChartCategoryModule } from "@infragistics/igniteui-react-charts" ;
import { IgrDataChartInteractivityModule } from "@infragistics/igniteui-react-charts" ;
import { IgrDataChartFinancialModule } from "@infragistics/igniteui-react-charts" ;
import { IgrNumericYAxis } from "@infragistics/igniteui-react-charts" ;
import { IgrCategoryXAxis } from "@infragistics/igniteui-react-charts" ;
import { IgrFinancialPriceSeries } from "@infragistics/igniteui-react-charts" ;
import { SampleFinancialData } from './SampleFinancialData' ;
IgrDataChartCoreModule.register();
IgrDataChartCategoryModule.register();
IgrDataChartFinancialModule.register();
IgrDataChartInteractivityModule.register();
export default class DataChartNavigation extends React.Component <any, any> {
public chart: IgrDataChart;
constructor (props: any ) {
super (props);
this .state = {
data: SampleFinancialData.create(),
defaultInteraction: "DragPan" ,
dragModifier: "Alt" ,
isZoomEnabled: true ,
panModifier: "Control" };
this .onChartRef = this .onChartRef.bind(this );
this .onDefaultInteractionChange = this .onDefaultInteractionChange.bind(this );
this .onPanModifierChange = this .onPanModifierChange.bind(this );
this .onDragModifierChange = this .onDragModifierChange.bind(this );
this .onZoomEnabledChange = this .onZoomEnabledChange.bind(this );
this .onPanDownClick = this .onPanDownClick.bind(this );
this .onPanLeftClick = this .onPanLeftClick.bind(this );
this .onPanRightClick = this .onPanRightClick.bind(this );
this .onPanUpClick = this .onPanUpClick.bind(this );
this .onZoomInClick = this .onZoomInClick.bind(this );
this .onZoomOutClick = this .onZoomOutClick.bind(this );
}
public render (): JSX .Element {
return (
<div className ="container sample" >
<div className ="options horizontal" >
<div className ="options vertical" style ={{width: "100px "}}>
<button onClick ={this.onPanUpClick} > Pan Up</button >
<button onClick ={this.onPanDownClick} > Pan Down</button >
</div >
<div className ="options vertical" style ={{width: "100px "}}>
<button onClick ={this.onPanLeftClick} > Pan Left</button >
<button onClick ={this.onPanRightClick} > Pan Right</button >
</div >
<div className ="options vertical" style ={{width: "100px "}}>
<button onClick ={this.onZoomInClick} > Zoom In</button >
<button onClick ={this.onZoomOutClick} > Zoom Out</button >
</div >
<div className ="options vertical" style ={{ width: "120px ", alignSelf: "center " }}>
<label className ="options-label" style ={{ margin: "5px " }}> Pan Modifier:</label >
<label className ="options-label" style ={{ margin: "5px " }}> Zoom Modifier:</label >
</div >
<div className ="options vertical" style ={{ width: "100px " }}>
<select value ={this.state.panModifier} style ={{ margin: "5px "}} onChange ={this.onPanModifierChange} >
<option > Alt</option >
<option > Control</option >
<option > Shift</option >
<option > Windows</option >
<option > Apple</option >
<option > None</option >
</select >
<select value ={this.state.dragModifier} style ={{ margin: "5px "}} onChange ={this.onDragModifierChange} >
<option > Alt</option >
<option > Control</option >
<option > Shift</option >
<option > Windows</option >
<option > Apple</option >
<option > None</option >
</select >
</div >
<div className ="options vertical" style ={{ width: "150px ", alignSelf: "center " }}>
<label className ="options-label" style ={{ margin: "5px "}}> Interaction:</label >
<label className ="options-label" style ={{ margin: "5px "}}> Zooming:</label >
</div >
<div className ="options vertical" style ={{ width: "100px " }}>
<select value ={this.state.defaultInteraction} style ={{ margin: "5px "}} onChange ={this.onDefaultInteractionChange} >
<option > DragZoom</option >
<option > DragPan</option >
<option > None</option >
</select >
<input type ="checkbox" checked ={this.state.isZoomEnabled} onChange ={this.onZoomEnabledChange} />
</div >
</div >
<div className ="container vertical" >
<IgrDataChart
ref ={this.onChartRef}
width ="100%"
height ="100%"
subtitle ="Stock Prices Series in Candlestick Display Type"
subtitleTopMargin ={10}
isHorizontalZoomEnabled ={this.state.isZoomEnabled}
isVerticalZoomEnabled ={this.state.isZoomEnabled}
panModifier ={this.state.panModifier}
dragModifier ={this.state.dragModifier}
defaultInteraction ={this.state.defaultInteraction}
dataSource ={this.state.data} >
<IgrCategoryXAxis
name ="xAxis"
label ="Label" />
<IgrNumericYAxis
name ="yAxis"
title ="Amount (in USD)"
titleRightMargin ={10}
labelRightMargin ={10}
labelHorizontalAlignment ="Left"
labelLocation ="OutsideRight" />
<IgrFinancialPriceSeries
name ="series1"
xAxisName ="xAxis"
yAxisName ="yAxis"
displayType ="Candlestick"
openMemberPath ="Open"
closeMemberPath ="Close"
highMemberPath ="High"
lowMemberPath ="Low"
volumeMemberPath ="Volume"
showDefaultTooltip ={true}
isTransitionInEnabled ={true}
title ="Price" />
</IgrDataChart >
</div >
</div >
);
}
public onChartRef(chart: IgrDataChart) {
if (!chart) { return ; }
this .chart = chart;
this .chart.actualWindowScaleHorizontal = 0.60 ;
this .chart.actualWindowScaleVertical = 0.60 ;
this .chart.actualWindowPositionVertical = 0.20 ;
this .chart.actualWindowPositionHorizontal = 0.20 ;
}
public onDefaultInteractionChange = (e: any ) => {
this .setState({ defaultInteraction: e.target.value });
}
public onPanModifierChange = (e: any ) => {
this .setState({ panModifier: e.target.value });
}
public onDragModifierChange = (e: any ) => {
this .setState({ dragModifier: e.target.value });
}
public onZoomEnabledChange = (e: any ) => {
this .setState({ isZoomEnabled: e.target.checked });
}
public onPanUpClick = (e: any ) => {
this .chart.actualWindowPositionVertical -= 0.05 ;
}
public onPanDownClick = (e: any ) => {
this .chart.actualWindowPositionVertical += 0.05 ;
}
public onPanLeftClick = (e: any ) => {
this .chart.actualWindowPositionHorizontal -= 0.05 ;
}
public onPanRightClick = (e: any ) => {
this .chart.actualWindowPositionHorizontal += 0.05 ;
}
public onZoomOutClick = (e: any ) => {
if (this .chart.actualWindowPositionHorizontal > 0.025 ) {
this .chart.actualWindowPositionHorizontal -= 0.025 ;
}
if (this .chart.actualWindowPositionVertical > 0.025 ) {
this .chart.actualWindowPositionVertical -= 0.025 ;
}
if (this .chart.actualWindowScaleHorizontal < 1.0) {
this.chart.actualWindowScaleHorizontal += 0.05;
}
if (this.chart.actualWindowScaleVertical < 1.0) {
this.chart.actualWindowScaleVertical += 0.05;
}
}
public onZoomInClick = (e: any) => {
if (this.chart.actualWindowPositionHorizontal < 1.0) {
this.chart.actualWindowPositionHorizontal += 0.025;
}
if (this.chart.actualWindowPositionVertical < 1.0) {
this.chart.actualWindowPositionVertical += 0.025;
}
if (this.chart.actualWindowScaleHorizontal > 0.05) {
this.chart.actualWindowScaleHorizontal -= 0.05;
}
if (this.chart.actualWindowScaleVertical > 0.05) {
this.chart.actualWindowScaleVertical -= 0.05;
}
}
}
// rendering above class to the React DOM
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<DataChartNavigation /> );
tsx コピー
Like this sample? Get access to our complete Ignite UI for React toolkit and start building your own apps in minutes. Download it for free.
이 샘플이 마음에 드시나요? 당사의 완전한 React 툴킷에 액세스하여 몇 분 만에 나만의 앱을 빌드하기 시작하세요. 무료로 다운로드하세요.
Chart Navigation with User Interactions
확대/축소가 기본적으로 설정되어 있는지 여부는 사용 중인 차트에 따라 다릅니다. 사용하는 IgrCategoryChart
경우 기본적으로 켜져 있지만 에는 IgrDataChart
없습니다. UI에서 탐색을 활성화하거나 비활성화하려면 확대/축소를 활성화하거나 비활성화하려는 방향에 따라 차트의 및/또는 isVerticalZoomEnabled
속성을 설정해야 isHorizontalZoomEnabled
합니다.
마우스를 클릭하거나 터치를 사용하여 간단히 확대/축소하거나 이동하는 것도 가능합니다. 데이터 차트의 defaultInteraction
속성은 마우스 클릭 또는 터치 이벤트에서 발생하는 상황을 결정합니다. 이 속성의 기본값은 DragZoom
이며 확대/축소가 활성화된 상태에서 이 속성으로 설정되면 클릭하고 끌면 차트의 확대/축소된 영역이 될 플롯 영역 위에 미리 보기 직사각형이 배치됩니다. 이 defaultInteraction
속성을 DragPan
으로 설정하여 패닝을 허용하거나 None
으로 설정하여 이러한 작업을 방지할 수도 있습니다.
Chart Navigation with Touch, Mouse and Keyboard
React 데이터 차트의 탐색은 터치, 마우스 또는 키보드로 수행할 수 있습니다. 다음 작업은 기본적으로 터치, 마우스 또는 키보드 작업을 사용하여 호출할 수 있습니다.
패닝 : 키보드의 🡐 🡒 🡑 🡓 방향키를 사용하거나, Shift 키를 누른 채 마우스로 클릭하고 드래그하거나, 터치를 통해 손가락을 누르고 이동합니다.
확대 : 키보드의 Page Up 키를 이용하거나, 마우스 휠을 위로 굴리거나, 핀치 터치로 확대할 수 있습니다.
축소 : 키보드의 Page Down 키를 사용하거나, 마우스 휠을 아래로 굴리거나, 핀치 터치를 통해 축소합니다.
차트 플롯 영역에 맞추기 : 키보드의 Home 키를 사용합니다. 이에 대한 마우스나 터치 작업은 없습니다.
영역 확대/축소 : defaultInteraction
속성이 기본값인 DragZoom
으로 설정된 플롯 영역 내에서 마우스를 클릭하고 드래그합니다.
dragModifier
및 panModifier
속성을 각각 설정하여 수정자 키를 사용하여 확대/축소 및 이동 작업을 활성화할 수도 있습니다. 이러한 속성은 다음 수정자 키로 설정할 수 있으며, 누르면 해당 작업이 실행됩니다.
수정자 값
해당 키
Shift
옮기다
Control
Ctrl 키
Windows
이기다
Apple
사과
None
열쇠 없음
verticalViewScrollbarMode
및 horizontalViewScrollbarMode
속성을 활성화하여 차트를 스크롤할 수 있습니다.
다음 옵션으로 구성할 수 있습니다.
Persistent
- 차트가 확대되는 동안 스크롤 막대는 항상 표시되고 완전히 축소되면 사라집니다.
Fading
- 사용 후 스크롤바가 사라지고 마우스가 해당 위치 근처에 있으면 다시 나타납니다.
FadeToLine
- 확대/축소를 사용하지 않을 때 스크롤 막대가 더 얇은 선으로 줄어듭니다.
None
- 기본값, 스크롤바가 표시되지 않습니다.
다음 예에서는 스크롤 막대를 활성화하는 방법을 보여줍니다.
export class MultipleStocks extends Array <Array <StockItem >> {
public static async fetch(): Promise <MultipleStocks> {
const dataSources: any [] = [
await this .getGoogleStock(),
await this .getAmazonStock(),
];
return new Promise <MultipleStocks>((resolve, reject ) => {
resolve(dataSources);
});
}
public static async getAmazonStock(): Promise <StockItem[]> {
let url = "https://static.infragistics.com/xplatform/data/stocks/stockAmazon.json" ;
let response = await fetch(url);
let jsonData = await response.json();
let stockData = this .convertData(jsonData);
(stockData as any ).__dataIntents = {
close : ["SeriesTitle/Amazon" ]
};
return new Promise <StockItem[]>((resolve, reject ) => {
resolve(stockData);
});
}
public static async getTeslaStock(): Promise <StockItem[]> {
let url = "https://static.infragistics.com/xplatform/data/stocks/stockTesla.json" ;
let response = await fetch(url);
let jsonData = await response.json();
let stockData = this .convertData(jsonData);
(stockData as any ).__dataIntents = {
close : ["SeriesTitle/Tesla" ]
};
return new Promise <StockItem[]>((resolve, reject ) => {
resolve(stockData);
});
}
public static async getMicrosoftStock(): Promise <StockItem[]> {
let url = "https://static.infragistics.com/xplatform/data/stocks/stockMicrosoft.json" ;
let response = await fetch(url);
let jsonData = await response.json();
let stockData = this .convertData(jsonData);
(stockData as any ).__dataIntents = {
close : ["SeriesTitle/Microsoft" ]
};
return new Promise <StockItem[]>((resolve, reject ) => {
resolve(stockData);
});
}
public static async getGoogleStock(): Promise <StockItem[]> {
let url = "https://static.infragistics.com/xplatform/data/stocks/stockGoogle.json" ;
let response = await fetch(url);
let jsonData = await response.json();
let stockData = this .convertData(jsonData);
(stockData as any ).__dataIntents = {
close : ["SeriesTitle/Google" ]
};
return new Promise <StockItem[]>((resolve, reject ) => {
resolve(stockData);
});
}
public static convertData(jsonData: any []): StockItem[] {
let stockItems: StockItem[] = [];
for (let json of jsonData) {
let parts = json.date.split("-" );
let item = new StockItem();
item.date = new Date (parts[0 ], parts[1 ], parts[2 ],13 ,0 ,0 );
item.open = json.open;
item.high = json.high;
item.low = json.low;
item.close = json.close;
item.volume = json.volume;
stockItems.push(item);
}
return stockItems;
}
}
export class StockItem {
public open?: number ;
public close?: number ;
public high?: number ;
public low?: number ;
public volume?: number ;
public date?: Date ;
}
ts コピー import React from 'react' ;
import ReactDOM from 'react-dom/client' ;
import './index.css' ;
import { IgrFinancialChartModule, IgrDataChartInteractivityModule, IgrLegendModule } from "@infragistics/igniteui-react-charts" ;
import { IgrFinancialChart } from "@infragistics/igniteui-react-charts" ;
import { MultipleStocks } from './MultipleStocks' ;
const mods : any [] = [
IgrFinancialChartModule,
IgrDataChartInteractivityModule,
IgrLegendModule
];
mods.forEach((m) => m.register());
export default class Sample extends React.Component <any, any> {
private chart: IgrFinancialChart
private chartRef(r: IgrFinancialChart) {
this .chart = r;
this .setState({});
}
constructor (props: any ) {
super (props);
this .chartRef = this .chartRef.bind(this );
}
public render (): JSX .Element {
return (
<div className ="container sample" >
<div className ="container fill" >
<IgrFinancialChart
ref ={this.chartRef}
isToolbarVisible ="false"
isVerticalZoomEnabled ="true"
isHorizontalZoomEnabled ="true"
dataSource ={this.multipleStocks}
verticalViewScrollbarMode ="Fading"
horizontalViewScrollbarMode ="Persistent"
zoomSliderType ="None"
windowRect ="0, 0, 0.5, 1" >
</IgrFinancialChart >
</div >
</div >
);
}
private _multipleStocks: MultipleStocks = null ;
private _isFetching: boolean = false ;
public get multipleStocks(): MultipleStocks {
if (this ._multipleStocks == null && !this ._isFetching)
{
this ._isFetching = true ;
( async () => { this ._multipleStocks = await (await MultipleStocks.fetch()); this .setState({}); })();
}
return this ._multipleStocks;
}
}
const root = ReactDOM.createRoot (document.getElementById('root' ));
root.render (<Sample /> );
tsx コピー
Chart Navigation through Code
Code navigation of the chart can only be used for the IgrDataChart control.
React 데이터 차트는 차트에서 확대/축소 또는 팬 작업이 발생할 때마다 업데이트되는 여러 탐색 속성을 제공합니다. 이러한 각 속성을 설정하여 데이터 차트를 프로그래밍 방식으로 확대/축소 또는 팬할 수도 있습니다. 다음은 이러한 속성의 목록입니다.
Additional Resources
다음 항목에서 관련 차트 기능에 대한 자세한 내용을 확인할 수 있습니다.
API References
다음은 위 섹션에서 언급된 API 멤버 목록입니다.