Making a Graph Panel
Here is the definition of type of props defined in @grafana-ui for Graph component.
export interface GraphProps {
ariaLabel?: string;
children?: JSX.Element | JSX.Element[];
series: GraphSeriesXY[];
timeRange: TimeRange; // NOTE: we should aim to make `time` a property of the axis, not force it for all graphs
timeZone?: TimeZone; // NOTE: we should aim to make `time` a property of the axis, not force it for all graphs
showLines?: boolean;
showPoints?: boolean;
showBars?: boolean;
width: number;
height: number;
isStacked?: boolean;
lineWidth?: number;
onHorizontalRegionSelected?: (from: number, to: number) => void;
}
series
prop holds the data you want to render in your graph. Each line that you see on a normal Grafana chart is of type GraphSeriesXY
. Each panel can render multiple lines for different metrics/variables and therefore series is an array of GraphSeriesXY
. We can construct series prop from props.data
.
All time-series data in Grafana is stored and used as an object of type DataFrame
. It is kind of like data frames in data science if you are familiar with them (like pandas dataframes). props.data.series
is of type DataFrame[]
, ie. you have a collection of time-series data stored as an array. Each item in this array corresponds to a single element in your GraphSeriesXY[]
array. We have to therefore map object of type DataFrame
to object of type GraphSeriesXY
.
let ser_ind:number = 0;
const series:GraphSeriesXY[] = props.data.series.map(item => {
const timeVals:Array<GraphSeriesValue> = item
.fields[0]
.values
.toArray();
const yVals:Array<GraphSeriesValue> = item
.fields[1]
.values
.toArray();
const data:GraphSeriesValue[][] = [];
for (let i = 0; i < timeVals.length; i++) {
data.push([timeVals[i], yVals[i]]);
}
const unixTimeRange = (props.timeRange.to.unix() - props.timeRange.from.unix());
const ser:GraphSeriesXY = {
seriesIndex: ser_ind++,
yAxis: {index:0},
isVisible: true,
timeField: props.data.series[0].fields[0],
valueField: props.data.series[0].fields[1],
timeStep: props.width / unixTimeRange,
data: data,
};
return ser;
});
Each item
is of type DataFrame
. The time-series data is stored in the fields
array of item
. Each field
inside the fields
array consists of data points for a single axis similar to column-oriented dbms.
We have two axis in our graphs, time
(fields[0]
, x axis) and values
(fields[1], y axis). We construct data of type GraphSeriesValue[][]
. We create ser
using data
, fields
and timeRange
in unix values. From this transformation we get a series
array which can be passed to Graph
component. Make sure to give a distinct index to each item in series
(ser_ind
here). You can take a look at type GraphSeriesXY
if you want to play around with other props like color, etc.