recharts#CartesianGrid TypeScript Examples
The following examples show how to use
recharts#CartesianGrid.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimpleLineChart.tsx From react-tutorials with MIT License | 7 votes |
SimpleLineChart = (props: ISimpleLineChartProps) => {
return (
<>
<LineChart
width={500}
height={300}
data={props.data}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
height={60}
dataKey="date"
// @ts-ignore
tick={<CustomizedAxisTick />}
/>
<YAxis
// @ts-ignore
tick={<CustomizedYAxisTick />}
/>
<Tooltip />
<Line type="monotone" dataKey="value" stroke="#8884d8" dot={<EmptyDot />} />
</LineChart>
</>
)
}
Example #2
Source File: BuildTimeline.tsx From backstage with Apache License 2.0 | 6 votes |
BuildTimeline = ({
targets,
height,
width,
}: BuildTimelineProps) => {
const theme = useTheme();
if (!targets.length) return <p>No Targets</p>;
const data = getTimelineData(targets);
return (
<ResponsiveContainer
height={height}
width={width}
minHeight={EMPTY_HEIGHT + targets.length * 5}
>
<BarChart layout="vertical" data={data} maxBarSize={10} barGap={0}>
<CartesianGrid strokeDasharray="2 2" />
<XAxis type="number" domain={[0, 'dataMax']} />
<YAxis type="category" dataKey="name" padding={{ top: 0, bottom: 0 }} />
<Tooltip content={<TargetToolTip />} />
<Legend />
<Bar
dataKey="buildTime"
fill={theme.palette.grey[400]}
minPointSize={1}
/>
<Bar dataKey="compileTime" fill={theme.palette.primary.main} />
</BarChart>
</ResponsiveContainer>
);
}
Example #3
Source File: Debug.tsx From watchparty with MIT License | 6 votes |
Debug = () => {
const [data, setData] = useState([]);
// eslint-disable-next-line
useEffect(
(async () => {
const response = await fetch(timeSeriesUrl);
const json = await response.json();
json.reverse();
setData(json);
}) as any,
[setData]
);
const keys = Object.keys(data.slice(-1)[0] ?? {});
return (
<>
{keys.map((key) => (
<LineChart
width={1400}
height={400}
data={data}
margin={{
top: 5,
left: 20,
bottom: 5,
}}
>
<CartesianGrid />
<XAxis dataKey="time" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey={key} stroke="#8884d8" />
</LineChart>
))}
</>
);
}
Example #4
Source File: QueueSizeChart.tsx From asynqmon with MIT License | 6 votes |
function QueueSizeChart(props: Props) {
const theme = useTheme();
const handleClick = (params: { activeLabel?: string } | null) => {
const allQueues = props.data.map((b) => b.queue);
if (
params &&
params.activeLabel &&
allQueues.includes(params.activeLabel)
) {
history.push(queueDetailsPath(params.activeLabel));
}
};
const history = useHistory();
return (
<ResponsiveContainer>
<BarChart
data={props.data}
maxBarSize={120}
onClick={handleClick}
style={{ cursor: "pointer" }}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="queue" stroke={theme.palette.text.secondary} />
<YAxis stroke={theme.palette.text.secondary} />
<Tooltip />
<Legend />
<Bar dataKey="active" stackId="a" fill="#1967d2" />
<Bar dataKey="pending" stackId="a" fill="#669df6" />
<Bar dataKey="aggregating" stackId="a" fill="#e69138" />
<Bar dataKey="scheduled" stackId="a" fill="#fdd663" />
<Bar dataKey="retry" stackId="a" fill="#f666a9" />
<Bar dataKey="archived" stackId="a" fill="#ac4776" />
<Bar dataKey="completed" stackId="a" fill="#4bb543" />
</BarChart>
</ResponsiveContainer>
);
}
Example #5
Source File: ProcessedTasksChart.tsx From asynqmon with MIT License | 6 votes |
function ProcessedTasksChart(props: Props) {
const theme = useTheme<Theme>();
return (
<ResponsiveContainer>
<BarChart data={props.data} maxBarSize={120}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="queue" stroke={theme.palette.text.secondary} />
<YAxis stroke={theme.palette.text.secondary} />
<Tooltip />
<Legend />
<Bar
dataKey="succeeded"
stackId="a"
fill={theme.palette.success.light}
/>
<Bar dataKey="failed" stackId="a" fill={theme.palette.error.light} />
</BarChart>
</ResponsiveContainer>
);
}
Example #6
Source File: DailyStatsChart.tsx From asynqmon with MIT License | 6 votes |
export default function DailyStatsChart(props: Props) {
const data = makeChartData(props.data, props.numDays);
const theme = useTheme<Theme>();
return (
<ResponsiveContainer>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
dataKey="date"
minTickGap={10}
stroke={theme.palette.text.secondary}
/>
<YAxis stroke={theme.palette.text.secondary} />
<Tooltip />
<Legend />
<Line
type="monotone"
dataKey="succeeded"
stroke={theme.palette.success.main}
/>
<Line
type="monotone"
dataKey="failed"
stroke={theme.palette.error.main}
/>
</LineChart>
</ResponsiveContainer>
);
}
Example #7
Source File: ChartCard.tsx From genshin-optimizer with MIT License | 6 votes |
function Chart({ displayData, plotNode, valueNode, showMin }: {
displayData: Point[],
plotNode: NumNode,
valueNode: NumNode,
showMin: boolean
}) {
const plotBaseUnit = KeyMap.unit(plotNode.info?.key)
const valueUnit = KeyMap.unit(valueNode.info?.key)
return <ResponsiveContainer width="100%" height={600}>
<ComposedChart data={displayData}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="x" scale="linear" unit={plotBaseUnit} domain={["auto", "auto"]} tick={{ fill: 'white' }} type="number" tickFormatter={n => n > 10000 ? n.toFixed() : n.toFixed(1)} />
<YAxis name="DMG" domain={["auto", "auto"]} unit={valueUnit} allowDecimals={false} tick={{ fill: 'white' }} type="number" />
<ZAxis dataKey="y" range={[3, 25]} />
<Legend />
<Scatter name="Optimization Target" dataKey="y" fill="#8884d8" line lineType="fitting" isAnimationActive={false} />
{showMin && <Line name="Minimum Stat Requirement Threshold" dataKey="min" stroke="#ff7300" type="stepBefore" connectNulls strokeWidth={2} isAnimationActive={false} />}
</ComposedChart>
</ResponsiveContainer>
}
Example #8
Source File: ScatterChart.tsx From opensaas with MIT License | 6 votes |
ScatterChart: React.FC<ScatterChartProps> = (props: ScatterChartProps) => {
const { data, width, height, showGrid, strokeColor, fillColor, scatterName } = props;
return (
<ResponsiveContainer>
<RechartsScatterChart width={width} height={height}>
{showGrid ? <CartesianGrid strokeDasharray='3 3' /> : null}
<XAxis type='number' dataKey='x' name={data?.xname} tickLine={false} />
<YAxis type='number' dataKey='y' name={data?.yname} tickLine={false} />
<Tooltip />
<Legend
verticalAlign='top'
content={<CustomizedLegend strokeColor={strokeColor} fillColor={fillColor} scatterName={scatterName} />}
/>
<Scatter
name={scatterName}
data={data.lineChartData}
shape={<CustomizedDot strokeColor={strokeColor} fillColor={fillColor} r={6} cx={10} cy={10} />}
/>
</RechartsScatterChart>
</ResponsiveContainer>
);
}
Example #9
Source File: LineChart.tsx From opensaas with MIT License | 6 votes |
LineChart: React.FC<LineChartProps> = (props) => {
const { width, height, data, xAxis, line, showGrid, colors } = props;
return (
<ResponsiveContainer>
<RechartsLineChart width={width} height={height}>
{showGrid ? <CartesianGrid strokeDasharray='3 3' /> : null}
<XAxis dataKey='category' type={xAxis.type} allowDuplicatedCategory={false} axisLine={false} tickLine={false} />
<YAxis dataKey='value' axisLine={false} tickLine={false} />
<Tooltip />
<Legend verticalAlign='top' />
{data.map(({ data, name }, index: number) => (
<Line
strokeWidth={line.strokeWidth}
legendType='circle'
type={line.type}
stroke={colors[index % colors.length]}
dataKey='value'
data={data}
name={name}
key={name}
activeDot={line.activeDot}
/>
))}
</RechartsLineChart>
</ResponsiveContainer>
);
}
Example #10
Source File: BarChart.tsx From opensaas with MIT License | 6 votes |
BarChart: React.FC<BarChartProps> = (props) => {
const { width, height, data, barSize, barCategoryGap, showGrid, showLegend, colors } = props;
return (
<ResponsiveContainer>
<RechartsBarChart
width={width}
height={height}
data={data}
barSize={barSize}
barCategoryGap={barCategoryGap}
margin={{
top: 5,
right: 30,
left: 10,
bottom: 5,
}}>
{showGrid ? <CartesianGrid strokeDasharray='3 3' /> : null}
<XAxis dataKey='name' axisLine={false} tickLine={false} />
<YAxis axisLine={false} tickLine={false} />
<Tooltip cursor={false} />
{showLegend ? <Legend /> : null}
{Object.keys(data[0]).map((key: string, index: number) => {
return key !== 'name' ? <Bar dataKey={key} key={key} fill={colors[(index - 1) % colors.length]} /> : null;
})}
</RechartsBarChart>
</ResponsiveContainer>
);
}
Example #11
Source File: TrafficChart.tsx From web-show with Apache License 2.0 | 6 votes |
TrafficChart: React.FC<IProps> = props => {
const { data } = props;
return (
<ResponsiveContainer>
<ComposedChart
barGap="2%"
width={600}
height={400}
margin={{
top: 10,
right: 30,
left: 20,
bottom: 20
}}
data={data}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
tickLine={false}
dataKey="time"
domain = {['auto', 'auto']}
tickFormatter = {(unixTime) => moment(unixTime).format('HH:mm:ss Do')}
type = 'number'
/>
<YAxis label={{ value: 'Latency', position: 'insideLeft', angle: -90 }} unit={"ms"}/>
<Tooltip labelFormatter={t => new Date(t).toLocaleString()} />
<Legend />
<Line type="monotone" dataKey="latency" stroke="#8884d8" />
</ComposedChart>
</ResponsiveContainer>
);
}
Example #12
Source File: index.tsx From Demae with MIT License | 6 votes |
OrderChart = () => {
return (
<LineChart
width={500}
height={300}
data={data}
margin={{
top: 5, right: 30, left: 20, bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="pv" stroke="#8884d8" activeDot={{ r: 8 }} />
<Line type="monotone" dataKey="uv" stroke="#82ca9d" />
</LineChart>
);
}
Example #13
Source File: WeeklyIncidentsSeverity.tsx From backstage-plugin-opsgenie with MIT License | 6 votes |
Graph = ({context}: {context: Context}) => {
const analyticsApi = useApi(analyticsApiRef);
const dataPoints = analyticsApi.incidentsByWeekAndSeverity(context);
return (
<div id="weekly-incidents-severity" style={{ width: '100%', height: 300, paddingTop: '1.2rem', paddingRight: '1.2rem' }}>
<ResponsiveContainer>
<ComposedChart data={dataPoints}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="week" />
<YAxis />
<Bar dataKey="p1" fill="#bf2600" name="P1 - Critical" stackId="a" barSize={30} />
<Bar dataKey="p2" fill="#ff7452" name="P2 - High" stackId="a" barSize={30} />
<Bar dataKey="p3" fill="#ffab00" name="P3 - Moderate" stackId="a" barSize={30} />
<Bar dataKey="p4" fill="#36b37e" name="P4 - Low" stackId="a" barSize={30} />
<Bar dataKey="p5" fill="#00857A" name="P5 - Informational" stackId="a" barSize={30} />
<Tooltip content={<FilterZeroTooltip />} />
<Legend />
</ComposedChart>
</ResponsiveContainer>
</div>
);
}
Example #14
Source File: WeeklyIncidents.tsx From backstage-plugin-opsgenie with MIT License | 6 votes |
Graph = ({context}: {context: Context}) => {
const analyticsApi = useApi(analyticsApiRef);
const dataPoints = analyticsApi.incidentsByWeekAndHours(context);
return (
<div id="weekly-incidents" style={{ width: '100%', height: 300, paddingTop: '1.2rem', paddingRight: '1.2rem' }}>
<ResponsiveContainer>
<ComposedChart
data={dataPoints}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="week" />
<YAxis />
<Bar dataKey="businessHours" fill="#82ca9d" name="Business hours" stackId="a" barSize={30} />
<Bar dataKey="onCallHours" fill="#8884d8" name="On-call hours" stackId="a" barSize={30} />
<Line type="monotone" dataKey="total" name="Total" stroke="#ff7300" />
<Tooltip content={<FilterZeroTooltip />} />
<Legend />
</ComposedChart>
</ResponsiveContainer>
</div>
);
}
Example #15
Source File: WeeklyImpactResponder.tsx From backstage-plugin-opsgenie with MIT License | 6 votes |
WeeklyImpactResponders = ({ context }: { context: Context }) => {
const graphId = "weekly-impact-responders";
const analyticsApi = useApi(analyticsApiRef);
const data = analyticsApi.impactByWeekAndResponder(context);
return (
<InfoCard title="Average impact by week and responder" action={<SaveAction targetRef={graphId} />}>
<div id={graphId} style={{ width: '100%', height: 450, paddingTop: '1.2rem', paddingRight: '1.2rem' }}>
<ResponsiveContainer>
<ComposedChart data={data.dataPoints}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="period" />
<YAxis tickFormatter={value => value === 0 ? '0 min' : moment.duration(value, 'minutes').humanize()} />
{data.responders.map(responder => (
<Bar dataKey={responder} fill={colorForString(responder)} stackId="a" barSize={30} key={responder} />
))}
<Tooltip
formatter={(value: number, name: string) => [value === 0 ? '0 min' : moment.duration(value, 'minutes').humanize(), name]}
content={<FilterZeroTooltip />}
/>
<Legend />
</ComposedChart>
</ResponsiveContainer>
</div>
</InfoCard>
);
}
Example #16
Source File: PeriodByResponderGraph.tsx From backstage-plugin-opsgenie with MIT License | 6 votes |
PeriodByResponderGraph = ({data}: {data: IncidentsByResponders}) => {
return (
<ResponsiveContainer>
<ComposedChart data={data.dataPoints}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="period" />
<YAxis />
{data.responders.map(responder => (
<Bar dataKey={responder} fill={colorForString(responder)} stackId="a" barSize={30} key={responder} />
))}
<Line type="monotone" dataKey="total" name="Total" stroke="#ff7300" />
<Tooltip content={<FilterZeroTooltip />} />
<Legend />
</ComposedChart>
</ResponsiveContainer>
);
}
Example #17
Source File: HourlyIncidents.tsx From backstage-plugin-opsgenie with MIT License | 6 votes |
Graph = ({context}: {context: Context}) => {
const analyticsApi = useApi(analyticsApiRef);
const dataPoints = analyticsApi.incidentsByHour(context);
return (
<div id="hourly-incidents" style={{ width: '100%', height: 300, paddingTop: '1.2rem', paddingRight: '1.2rem' }}>
<ResponsiveContainer>
<ScatterChart data={dataPoints}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="hour" name="Hour" unit="h" />
<YAxis dataKey="total" name="Total" />
<Tooltip content={<FilterZeroTooltip />} />
<Scatter name="Hour" data={dataPoints} fill="#8884d8" />
</ScatterChart>
</ResponsiveContainer>
</div>
);
}
Example #18
Source File: DailyIncidents.tsx From backstage-plugin-opsgenie with MIT License | 6 votes |
Graph = ({context}: {context: Context}) => {
const analyticsApi = useApi(analyticsApiRef);
const dataPoints = analyticsApi.incidentsByDay(context);
return (
<div id="daily-incidents" style={{ width: '100%', height: 300, paddingTop: '1.2rem', paddingRight: '1.2rem' }}>
<ResponsiveContainer>
<ScatterChart data={dataPoints}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="day" name="Day" />
<YAxis dataKey="total" name="Total" />
<Tooltip content={<FilterZeroTooltip />} />
<Scatter name="day" data={dataPoints} fill="#8884d8" />
</ScatterChart>
</ResponsiveContainer>
</div>
);
}
Example #19
Source File: stats.tsx From config-generator with MIT License | 5 votes |
public render() {
const { stats, onRefresh, range } = this.props;
const { strokeWidth } = this.state;
return (
<ResponsiveContainer width="100%" maxHeight={500} aspect={4.0 / 3.0}>
<LineChart
data={stats}
margin={{
top: 25,
right: 30,
left: 20,
bottom: 100,
}}
>
<CartesianGrid strokeDasharray="1 4" />
<XAxis
dataKey="timeStamp"
tick={this.renderCustomAxisTick}
interval={0}
ticks={stats.map((s: any) => s.timeStamp)}
type="number"
domain={['dataMin', 'dataMax']}
/>
<YAxis />
<Tooltip
itemStyle={{ textTransform: 'capitalize' }}
labelFormatter={value =>
range === 'day'
? moment(value).format('DD/MM/YYYY HH:mm:ss')
: moment(value).format('DD/MM/YYYY')
}
labelStyle={{ fontWeight: 'bold', marginBottom: '10px' }}
/>
<Legend
verticalAlign="top"
iconType="circle"
formatter={(value, entry, index) => value.toUpperCase()}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
/>
<Line
type="monotone"
dataKey="all"
connectNulls={true}
stroke="#4F4F4F"
activeDot={{ r: 8 }}
strokeWidth={strokeWidth.all}
/>
<Line
type="monotone"
dataKey="allowed"
stroke="#71ADFE"
connectNulls={true}
activeDot={{ r: 8 }}
strokeWidth={strokeWidth.allowed}
/>
<Line
type="monotone"
connectNulls={true}
dataKey="blocked"
stroke="#EB5757"
activeDot={{ r: 8 }}
strokeWidth={strokeWidth.blocked}
/>
</LineChart>
</ResponsiveContainer>
);
}
Example #20
Source File: OrderChart.tsx From ra-enterprise-demo with MIT License | 5 votes |
OrderChart: FC<{ orders?: Order[] }> = ({ orders }) => {
const translate = useTranslate();
if (!orders) return null;
return (
<Card>
<CardHeader title={translate('pos.dashboard.month_history')} />
<CardContent>
<div style={{ width: '100%', height: 300 }}>
<ResponsiveContainer>
<AreaChart data={getRevenuePerDay(orders)}>
<defs>
<linearGradient
id="colorUv"
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop
offset="5%"
stopColor="#8884d8"
stopOpacity={0.8}
/>
<stop
offset="95%"
stopColor="#8884d8"
stopOpacity={0}
/>
</linearGradient>
</defs>
<XAxis
dataKey="date"
name="Date"
type="number"
scale="time"
domain={[
addDays(aMonthAgo, 1).getTime(),
new Date().getTime(),
]}
tickFormatter={dateFormatter}
/>
<YAxis dataKey="total" name="Revenue" unit="€" />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip
cursor={{ strokeDasharray: '3 3' }}
formatter={(value): string =>
new Intl.NumberFormat(undefined, {
style: 'currency',
currency: 'USD',
}).format(value as any)
}
labelFormatter={(label: any): string =>
dateFormatter(label)
}
/>
<Area
type="monotone"
dataKey="total"
stroke="#8884d8"
strokeWidth={2}
fill="url(#colorUv)"
/>
</AreaChart>
</ResponsiveContainer>
</div>
</CardContent>
</Card>
);
}
Example #21
Source File: index.tsx From Lux-Viewer-2021 with Apache License 2.0 | 5 votes |
Graph = ({ data, ylabel, xlabel }: GraphProps) => {
const renderColorfulLegendText = (value: string, entry: any) => {
const { color } = entry;
return <span style={{ color: '#f9efe2' }}>{value}</span>;
};
return (
<div className="Graph">
<ResponsiveContainer width={'100%'} height={220}>
<LineChart
// width={200}
onClick={() => {}}
// height={150}
data={data}
margin={{ top: 15, right: 20, left: 0, bottom: 15 }}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name">
<Label
value={xlabel}
offset={-15}
position="insideBottom"
fill="#f9efe2"
/>
</XAxis>
<YAxis
label={{
value: ylabel,
angle: -90,
position: 'insideLeft',
fill: '#f9efe2',
color: 'f9efe2',
}}
></YAxis>
<Tooltip labelStyle={{ color: '#323D34' }} />
{/* <Legend
verticalAlign="top"
height={36}
formatter={renderColorfulLegendText}
/> */}
<Line
type="monotone"
dataKey="team0"
name="Team 0"
dot={false}
strokeWidth={2}
isAnimationActive={false}
stroke={TEAM_A_COLOR_STR}
/>
<Line
type="monotone"
dataKey="team1"
name="Team 1"
dot={false}
strokeWidth={2}
isAnimationActive={false}
stroke={TEAM_B_COLOR_STR}
/>
</LineChart>
</ResponsiveContainer>
</div>
);
}
Example #22
Source File: StatisticsChart.tsx From jitsu with MIT License | 5 votes |
StatisticsChart: React.FC<Props> = ({
data,
granularity,
dataToDisplay = ["success", "skip", "errors"],
legendLabels = {},
}) => {
const [state, dispatch] = useReducer(reducer, initialState)
const handleClickOnLegend = (data: any) => {
const clickedDataType = data["value"] as DataType
dispatch({ type: clickedDataType })
}
return (
<ResponsiveContainer width="100%" minHeight={225} minWidth={300}>
<LineChart
className={styles.chart}
data={data.map(point => ({
...point,
date: granularity == "hour" ? point.date.format("HH:mm") : point.date.format("DD MMM"),
}))}
>
<XAxis dataKey="date" tick={<CustomizedXAxisTick />} stroke="#394e5a" />
<YAxis tick={<CustomizedYAxisTick />} stroke="#394e5a" />
<CartesianGrid strokeDasharray="3 3" stroke="#394e5a" />
<Legend onClick={handleClickOnLegend} formatter={value => legendLabels[value] ?? value} />
<Tooltip
wrapperStyle={{
backgroundColor: "#22313a",
border: "1px solid #394e5a",
}}
itemStyle={{ color: "#9bbcd1" }}
labelStyle={{ color: "#dcf3ff" }}
formatter={value => new Intl.NumberFormat("en").format(value)}
/>
{dataToDisplay.includes("total") && (
<Line dataKey="total" stroke={"rgb(135, 138, 252)"} hide={state.hide_total_data} {...commonLineProps} />
)}
{dataToDisplay.includes("success") && (
<Line dataKey="success" stroke={"#2cc56f"} hide={state.hide_success_data} {...commonLineProps} />
)}
{dataToDisplay.includes("skip") && (
<Line dataKey="skip" stroke={"#ffc021"} hide={state.hide_skip_data} {...commonLineProps} />
)}
{dataToDisplay.includes("errors") && (
<Line dataKey="errors" stroke={"#e53935"} hide={state.hide_errors_data} {...commonLineProps} />
)}
</LineChart>
</ResponsiveContainer>
)
}
Example #23
Source File: QueueMetricsChart.tsx From asynqmon with MIT License | 5 votes |
function QueueMetricsChart(props: Props) {
const theme = useTheme();
const data = toChartData(props.data);
const keys = props.data.map((x) => x.metric.queue);
return (
<ResponsiveContainer height={260}>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
minTickGap={10}
dataKey="timestamp"
domain={[props.startTime, props.endTime]}
tickFormatter={(timestamp: number) =>
new Date(timestamp * 1000).toLocaleTimeString()
}
type="number"
scale="time"
stroke={theme.palette.text.secondary}
/>
<YAxis
tickFormatter={props.yAxisTickFormatter}
stroke={theme.palette.text.secondary}
/>
<Tooltip
labelFormatter={(timestamp: number) => {
return new Date(timestamp * 1000).toLocaleTimeString();
}}
/>
<Legend />
{keys.map((key, idx) => (
<Line
key={key}
type="monotone"
dataKey={key}
stroke={lineColors[idx % lineColors.length]}
dot={false}
/>
))}
</LineChart>
</ResponsiveContainer>
);
}
Example #24
Source File: index.tsx From korona-info with MIT License | 4 votes |
Index: NextPage<{ groupedCoronaData: GroupedData, hospitalised: HospitalData[] }> = ({
groupedCoronaData, hospitalised
}: {
groupedCoronaData: GroupedData;
hospitalised: HospitalData[];
}) => {
const [selectedHealthCareDistrict, selectHealthCareDistrict] = useState<
string
>('all');
const confirmed = groupedCoronaData[selectedHealthCareDistrict].confirmed;
const deaths = groupedCoronaData[selectedHealthCareDistrict].deaths;
const recovered = groupedCoronaData[selectedHealthCareDistrict].recovered;
const allConfirmed = groupedCoronaData.all.confirmed;
const toast = useToast()
const latestInfection = confirmed.length
? format(
utcToZonedTime(
new Date(confirmed[confirmed.length - 1].date),
timeZone
),
'dd.MM.yyyy - HH:mm',
{ timeZone }
)
: null;
const latestInfectionDistrict =
confirmed[confirmed.length - 1]?.healthCareDistrict;
const latestDeath = deaths.length
? format(
utcToZonedTime(new Date(deaths[deaths.length - 1].date), timeZone),
'd.M.yyyy'
)
: null;
const latestDeathDistrict = deaths.length
? deaths[deaths.length - 1].area
: null;
const latestRecoveredDistrict = recovered.length
? recovered[recovered.length - 1].healthCareDistrict
: null;
const latestRecovered = recovered.length
? format(
utcToZonedTime(
new Date(recovered[recovered.length - 1].date),
timeZone
),
'd.M.yyyy'
)
: null;
const infectionsToday = getInfectionsToday(confirmed);
const [cumulativeChartScale, setCumulativeChartScale] = useState<
'linear' | 'log'
>('linear');
const [forecastChartScale, setForecaseChartScale] = useState<
'linear' | 'log'
>('linear');
// Map data to show development of infections
const {
infectionDevelopmentData,
infectionDevelopmentData30Days
} = groupedCoronaData[selectedHealthCareDistrict].timeSeries;
const maxValues =
infectionDevelopmentData30Days[infectionDevelopmentData30Days.length - 1];
const dataMaxValue = Math.max(
maxValues?.deaths ?? 0,
maxValues?.infections ?? 0,
maxValues?.infections ?? 0
);
const {
infectionsByDistrict,
infectionsByDistrictPercentage,
areas
} = getTnfectionsByDistrict(allConfirmed);
const { infectionsBySourceCountry } = getInfectionsBySourceCountry(confirmed);
const networkGraphData = getNetworkGraphData(confirmed);
const { t } = useContext(UserContext);
const humanizeHealthcareDistrict = (district: string) => {
if (district === 'all') {
return t('All healthcare districts');
} else if (district === 'unknown') {
return t('unknown');
} else {
return district;
}
};
const reversedConfirmed = confirmed
// @ts-ignore
.map((i, index) => ({
index: index + 1,
...i,
healthCareDistrict: humanizeHealthcareDistrict(i.healthCareDistrict)
}))
.reverse();
const humanizedHealthCareDistrict = humanizeHealthcareDistrict(
selectedHealthCareDistrict
);
useEffect(() => {
if (typeof window !== undefined) {
toast({
position: 'bottom',
title: 'Datan lähteenä nyt THL',
description: 'HS:n datan lähde on vaihtunut THL:ään. THL:n tiedotussyklistä johtuen tiedot päivittyvät aiempaa harvemmin. Myös vanhemmissa tapauksissa voi olla päivämääräkohtaisia eroja, johtuen muuttuneesta raportointitavasta.',
status: "info",
isClosable: true,
duration: 14000,
});
}
}, [])
return (
<>
<Head>
<title>
{t('finland corona status')} - {t('cases')} : {confirmed.length || 0}{' '}
- {t('recovered')}: {recovered.length || 0} - {t('deaths')}:{' '}
{deaths.length || 0}
</title>
<meta
name="description"
content={`Suomen koronavirus-tartuntatilanne – tartunnat: ${confirmed.length ||
0} - parantuneet: ${recovered.length ||
0} - menehtyneet: ${deaths.length || 0}`}
/>
<meta property="og:title" content={t('finland corona status')} />
<meta
property="og:description"
content={`Tartuntoja tällä hetkellä: ${confirmed.length ||
0} - parantuneet: ${recovered.length ||
0} - menehtyneet: ${deaths.length || 0}`}
/>
<meta
property="og:site_name"
content="Suomen koronavirus-tartuntatilanne"
/>
<meta property="og:locale" content="fi_FI" />
<meta property="og:type" content="website" />
<meta property="og:image" content="/images/corona-virus.png" />
<meta property="og:image:width" content="1920" />
<meta property="og:image:height" content="1928" />
<meta property="og:url" content="https://korona.kans.io" />
</Head>
<Layout>
<Flex
alignItems="center"
flexDirection="column"
flex="1"
width={'100%'}
maxWidth="1440px"
margin="auto"
>
<Header />
<Flex
flexWrap="wrap"
flexDirection="row"
justifyContent="left"
alignItems="stretch"
flex="1"
width={'100%'}
>
<Box width={['100%', '100%', 1 / 3, 1 / 3]} p={3}>
<Select
value={selectedHealthCareDistrict ?? undefined}
onChange={event => selectHealthCareDistrict(event.target.value)}
>
<option key={'all'} value={'all'}>
{t('All healthcare districts')}
</option>
{healtCareDistricts.map(healthcareDistrict => (
<option
key={healthcareDistrict.name}
value={healthcareDistrict.name}
>
{healthcareDistrict.name}
</option>
))}
))}
</Select>
</Box>
</Flex>
<Flex
flexWrap="wrap"
flexDirection="row"
justifyContent="center"
alignItems="stretch"
flex="1"
width={'100%'}
>
<Box width={['100%', '100%', 1 / 2, 1 / 2]} p={3}>
<Block
title={t('cases') + ` (${humanizedHealthCareDistrict})`}
textAlign="center"
extraInfo={`${t('New cases today')} ${infectionsToday} ${t(
'person'
)}`}
footer={`${t(
'latest case'
)} ${latestInfection} (${humanizeHealthcareDistrict(
latestInfectionDistrict
)})`}
>
<StatBlock
count={confirmed.length}
helpText={`${t('New cases today')}: ${infectionsToday} ${t(
'person'
)}`}
/>
</Block>
</Box>
<Box width={['100%', '100%', 1 / 2, 1 / 2]} p={3}>
<Block
title={t('deaths') + ` (${humanizedHealthCareDistrict})`}
footer={
latestDeath
? `${t(
'last death'
)} ${latestDeath} (${humanizeHealthcareDistrict(
latestDeathDistrict!
)})`
: t('no death')
}
>
<StatBlock count={deaths.length || 0} />
</Block>
</Box>
{/* <Box width={['100%', '100%', 1 / 3, 1 / 3]} p={3}>
<Block
title={t('recovered') + ` (${humanizedHealthCareDistrict})`}
footer={
`${latestRecovered
? `${t(
'latest recovery'
)} ${latestRecovered} (${humanizeHealthcareDistrict(latestRecoveredDistrict!)}).`
: ' '} ${t('recoveredNotice')}`}
>
<StatBlock count={recovered.length || 0} />
</Block>
</Box> */}
<Box width={['100%']} p={3}>
<Block
title={
t('accumulated change') + ` (${humanizedHealthCareDistrict})`
}
footer={t('cases recovered and death in past 30 days')}
>
<ButtonGroup
spacing={0}
alignSelf="center"
display="flex"
justifyContent="center"
marginTop="-15px"
>
<Button
size="xs"
fontFamily="Space Grotesk Regular"
px={3}
letterSpacing="1px"
borderRadius="4px 0px 0px 4px"
borderWidth="0px"
isActive={cumulativeChartScale === 'linear'}
onClick={() => setCumulativeChartScale('linear')}
>
{t('linear')}
</Button>
<Button
size="xs"
fontFamily="Space Grotesk Regular"
px={3}
letterSpacing="1px"
borderRadius="0px 4px 4px 0px"
borderWidth="0px"
isActive={cumulativeChartScale === 'log'}
onClick={() => setCumulativeChartScale('log')}
>
{t('logarithmic')}
</Button>
</ButtonGroup>
<ResponsiveContainer width={'100%'} height={380}>
<ComposedChart
data={
cumulativeChartScale === 'log'
? infectionDevelopmentData30Days.map(zerosToNulls)
: infectionDevelopmentData30Days
}
margin={{ top: 20, right: 30, left: 0, bottom: 30 }}
>
<defs>
<linearGradient
id="colorInfection"
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop
offset="5%"
stopColor={colors[8]}
stopOpacity={0.6}
/>
<stop
offset="95%"
stopColor={colors[8]}
stopOpacity={0}
/>
</linearGradient>
<linearGradient
id="colorRecovered"
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop
offset="5%"
stopColor={colors[7]}
stopOpacity={0.6}
/>
<stop
offset="95%"
stopColor={colors[7]}
stopOpacity={0}
/>
</linearGradient>
<linearGradient
id="colorDeaths"
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop
offset="5%"
stopColor={colors[0]}
stopOpacity={0.6}
/>
<stop
offset="95%"
stopColor={colors[0]}
stopOpacity={0}
/>
</linearGradient>
</defs>
<XAxis
tickFormatter={d => format(new Date(d), 'd.M.')}
tick={<CustomizedAxisTick isDate />}
dataKey="date"
domain={['dataMin', 'dataMax']}
type="number"
scale="time"
/>
<YAxis
scale={cumulativeChartScale}
dataKey="infections"
domain={[
cumulativeChartScale === 'log' ? 1 : 0,
dataMaxValue + 10
]}
unit={' ' + t('person')}
tick={{ fontSize: 12 }}
name={t('cases')}
/>
<CartesianGrid opacity={0.2} />
<Tooltip
labelFormatter={v => format(new Date(v), 'dd.MM.yyyy')}
/>
<Bar
isAnimationActive={false}
fill={colors[1]}
opacity={0.4}
dataKey="infectionsDaily"
name={t('cases of the day')}
unit={' ' + t('person')}
/>
<Area
isAnimationActive={false}
type="monotone"
unit={' ' + t('person')}
name={t('total cases')}
dataKey="infections"
stroke={colors[8]}
fillOpacity={1}
fill="url(#colorInfection)"
/>
{/* <Area
isAnimationActive={false}
type="monotone"
unit={' ' + t('person')}
name={t('total recovered')}
dataKey="recovered"
stroke={colors[7]}
fillOpacity={1}
fill="url(#colorRecovered)"
/> */}
<Area
isAnimationActive={false}
type="monotone"
unit={' ' + t('person')}
name={t('total deaths')}
dataKey="deaths"
stroke={colors[0]}
fillOpacity={1}
fill="url(#colorDeaths)"
/>
<Legend wrapperStyle={{ bottom: '10px' }} />
</ComposedChart>
</ResponsiveContainer>
</Block>
</Box>
{/*
<Box width={['100%']} p={3}>
<Block title="Tartuntojen kumulatiivinen ennustemalli" footer={`Tartuntojen kehityksen ennustemalli 60 päivää. Laskee ennustetun eksponentiaalisen kasvun käyttämällä aiemmin luotuja tietoja. Käytetty <a style="color: #319795;" href="https://github.com/mljs/regression-exponential" target="_blank">exponential-regression</a> kirjastoa.`}>
<ButtonGroup spacing={0} alignSelf="center" display="flex" justifyContent="center" marginTop="-15px">
<Button size="xs" fontFamily="Space Grotesk Regular" px={3} letterSpacing="1px" borderRadius="4px 0px 0px 4px" borderWidth="0px" isActive={forecastChartScale === 'linear'} onClick={() => setForecaseChartScale('linear')}>
Lineaarinen
</Button>
<Button size="xs" fontFamily="Space Grotesk Regular" px={3} letterSpacing="1px" borderRadius="0px 4px 4px 0px" borderWidth="0px" isActive={forecastChartScale === 'log'} onClick={() => setForecaseChartScale('log')}>
Logaritminen
</Button>
</ButtonGroup>
<ResponsiveContainer width={'100%'} height={350}>
<AreaChart
data={prediction60Days}
margin={{ top: 20, right: 30, left: 0, bottom: 20 }}
>
<defs>
<linearGradient id="colorInfection" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={colors[8]} stopOpacity={0.6} />
<stop offset="95%" stopColor={colors[8]} stopOpacity={0} />
</linearGradient>
</defs>
<XAxis tickFormatter={d => format(new Date(d), 'd.M.')} tick={<CustomizedAxisTick isDate />} dataKey="date" domain={['dataMin', 'dataMax']} type="number" scale="time" />
<YAxis scale={forecastChartScale} dataKey="infections" domain={['auto', 'auto']} unit={' ' + t('person') } tick={{ fontSize: 12 }} name="Tartunnat" />
<CartesianGrid opacity={0.2} />
<ReferenceLine
x={today}
stroke="rgba(0,0,0,.5)"
// @ts-ignore
label={{ position: 'top', value: 'Nyt', fill: 'rgba(0,0,0,0.5)', fontSize: 12 }}
strokeDasharray="3 3" />
<Tooltip labelFormatter={v => format(new Date(v), 'dd.MM.yyyy')} />
<Area type="monotone" name="Ennuste" unit={' ' + t('person') } dataKey="infections" stroke={colors[8]} fillOpacity={1} fill="url(#colorInfection)" />
</AreaChart>
</ResponsiveContainer>
</Block>
</Box>
*/}
<Box width={['100%', '100%', '100%', '100%', 1 / 2]} p={3}>
<Block
title={t('Cases by district')}
footer={t('Helsinki metropolitan area is shown as HUS')}
>
<ResponsiveContainer width={'100%'} height={350}>
<BarChart
data={infectionsByDistrict}
margin={{
top: 20,
right: 30,
left: 0,
bottom: 85
}}
>
<XAxis
interval={0}
dataKey="name"
tick={<CustomizedAxisTick />}
/>
<YAxis
yAxisId="left"
unit={' ' + t('person')}
dataKey="infections"
tick={{ fontSize: 12 }}
/>
<Tooltip />
<Bar
isAnimationActive={false}
dataKey="infections"
name={t('cases')}
unit={' ' + t('person')}
yAxisId="left"
>
{areas.map((area, index) => (
<Cell key={area} fill={colors[index % colors.length]} />
))}
<LabelList
dataKey="infections"
position="top"
formatter={e => e}
/>
</Bar>
</BarChart>
</ResponsiveContainer>
</Block>
</Box>
<Box width={['100%', '100%', '100%', '100%', 1 / 2]} p={3}>
<Block
title={t('infectionsPerDisrictAndSize')}
footer={t('infectionsPerDisrictAndSize')}
>
<ResponsiveContainer width={'100%'} height={350}>
<BarChart
data={infectionsByDistrictPercentage}
margin={{
top: 20,
right: 30,
left: 0,
bottom: 85
}}
>
<XAxis
interval={0}
dataKey="name"
tick={<CustomizedAxisTick />}
/>
<YAxis
unit=" %"
dataKey="perDistrict"
tick={{ fontSize: 12 }}
/>
<Tooltip />
<Bar isAnimationActive={false} dataKey="perDistrict" name="%-osuus väestöstä" unit=" %">
{areas.map((area, index) => (
<Cell key={area} fill={colors[index % colors.length]} />
))}
<LabelList
dataKey="perDistict"
position="top"
formatter={e => e}
/>
</Bar>
</BarChart>
</ResponsiveContainer>
</Block>
</Box>
<Box width={['100%', '100%', '100%', '100%', 1 / 2]} p={3}>
<Block
title={t('log') + ` (${humanizedHealthCareDistrict})`}
footer={t('logFooter')}
>
<Table
height={500}
data={reversedConfirmed}
columns={useMemo(() => infectionColumns, [])}
/>
</Block>
</Box>
<BubbleChart data={groupedCoronaData} />
{/* <Box width={['100%', '100%', '100%', '100%', 1 / 2]} p={3}>
<Block
title={
t('infectionNetwork') + ` (${humanizedHealthCareDistrict})`
}
footer={t('infectionNetworkFooter')}
>
<NetworkGraph data={networkGraphData} />
</Block>
</Box> */}
<Box width={['100%']} p={3}>
<Block
title={
t('hospitalizedData') + ` (${t('All healthcare districts')})`
}
>
<ResponsiveContainer width={'100%'} height={350}>
<BarChart
data={hospitalised.slice(Math.max(hospitalised.length - 30, 0))}
margin={{
top: 20,
right: 30,
left: 0,
bottom: 85
}}
>
<XAxis
interval={0}
dataKey="dateString"
tick={<CustomizedAxisTick />}
padding={{ left: 50, right: 50 }}
/>
<YAxis
unit={' ' + t('person')}
dataKey="totalHospitalised"
tick={{ fontSize: 12 }}
/>
<Tooltip />
<Bar
isAnimationActive={false}
stackId="a"
dataKey="inIcu"
name={t("inIcu")}
unit={' ' + t('person')}
fill="#F3858D"
/>
<Bar
isAnimationActive={false}
stackId="a"
dataKey="inWard"
name={t("inWard")}
unit={' ' + t('person')}
fill="#2FAB8E"
/>
<Bar
isAnimationActive={false}
stackId="a"
dataKey="totalHospitalised"
opacity={0}
name={t("inHospital")}
unit={' ' + t('person')}
fill="rgba(0,0,0,1)"
strokeWidth={0}
legendType="none"
/>
<Legend wrapperStyle={{ bottom: '15px' }} />
</BarChart>
</ResponsiveContainer>
</Block>
</Box>
</Flex>
<Copyright />
</Flex>
</Layout>
</>
);
}
Example #25
Source File: status-chart.tsx From backstage with Apache License 2.0 | 4 votes |
export function StatusChart(props: StatusChartProps) {
const { analysis } = props;
const { zoomFilterValues } = useZoom();
const { zoomProps, getZoomArea } = useZoomArea();
const values = useMemo(() => {
return analysis.daily.values.map(value => {
const totTriggers = analysis.daily.triggerReasons.reduce(
(prev, cur) => prev + (value[cur as TriggerReason] ?? 0),
0,
);
if (!totTriggers) {
return value;
}
return {
...value,
...Object.fromEntries(
analysis.daily.triggerReasons.map(reason => [
reason,
(value[reason as TriggerReason] ?? 0) / totTriggers,
]),
),
};
});
}, [analysis.daily]);
const triggerReasonLegendPayload = useMemo(
(): NonNullable<LegendProps['payload']> =>
analysis.daily.triggerReasons.map(reason => ({
value: humanTriggerReason(reason),
type: 'line',
id: reason,
color: triggerColorMap[reason as TriggerReason] ?? '',
})),
[analysis.daily.triggerReasons],
);
const statusesLegendPayload = useMemo(
(): NonNullable<LegendProps['payload']> =>
analysis.daily.statuses.map(status => ({
value: capitalize(status),
type: 'line',
id: status,
color: statusColorMap[status as FilterStatusType] ?? '',
})),
[analysis.daily.statuses],
);
const legendPayload = useMemo(
(): NonNullable<LegendProps['payload']> => [
...triggerReasonLegendPayload,
...statusesLegendPayload,
],
[statusesLegendPayload, triggerReasonLegendPayload],
);
const tooltipFormatter = useMemo(() => {
const reasonSet = new Set(analysis.daily.triggerReasons);
return (percentOrCount: number, name: string) => {
const label = reasonSet.has(name)
? humanTriggerReason(name)
: capitalize(name);
const valueText = reasonSet.has(name)
? `${(percentOrCount * 100).toFixed(0)}%`
: percentOrCount;
return [
<span>
{label}: {valueText}
</span>,
null,
];
};
}, [analysis.daily.triggerReasons]);
const zoomFilteredValues = useMemo(
() => zoomFilterValues(values),
[values, zoomFilterValues],
);
const barSize = getBarSize(analysis.daily.values.length);
return (
<Accordion defaultExpanded={analysis.daily.statuses.length > 1}>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography>
Build count per status over build trigger reason
</Typography>
</AccordionSummary>
<AccordionDetails>
{values.length === 0 ? (
<Alert severity="info">No data</Alert>
) : (
<ResponsiveContainer width="100%" height={140}>
<ComposedChart data={zoomFilteredValues} {...zoomProps}>
<Legend payload={legendPayload} />
<CartesianGrid strokeDasharray="3 3" />
<XAxis
dataKey="__epoch"
type="category"
tickFormatter={tickFormatterX}
/>
<YAxis yAxisId={1} type="number" tickCount={5} name="Count" />
<YAxis yAxisId={2} type="number" name="Triggers" hide />
<Tooltip
labelFormatter={labelFormatterWithoutTime}
formatter={tooltipFormatter}
/>
{triggerReasonLegendPayload.map(reason => (
<Fragment key={reason.id}>
<Area
isAnimationActive={false}
type="monotone"
dataKey={reason.id!}
stackId="triggers"
yAxisId={2}
stroke={triggerColorMap[reason.id as TriggerReason] ?? ''}
fillOpacity={0.5}
fill={triggerColorMap[reason.id as TriggerReason] ?? ''}
/>
</Fragment>
))}
{[...analysis.daily.statuses].reverse().map(status => (
<Fragment key={status}>
<Bar
isAnimationActive={false}
type="monotone"
barSize={barSize}
dataKey={status}
stackId="statuses"
yAxisId={1}
stroke={statusColorMap[status as FilterStatusType] ?? ''}
fillOpacity={0.8}
fill={statusColorMap[status as FilterStatusType] ?? ''}
/>
</Fragment>
))}
{getZoomArea({ yAxisId: 1 })}
</ComposedChart>
</ResponsiveContainer>
)}
</AccordionDetails>
</Accordion>
);
}
Example #26
Source File: STResults.tsx From console with GNU Affero General Public License v3.0 | 4 votes |
STResults = ({ classes, results, start }: ISTResults) => {
const [jsonView, setJsonView] = useState<boolean>(false);
const finalRes = results[results.length - 1] || [];
const getServers: STServer[] = get(finalRes, "GETStats.servers", []) || [];
const putServers: STServer[] = get(finalRes, "PUTStats.servers", []) || [];
const getThroughput = get(finalRes, "GETStats.throughputPerSec", 0);
const getObjects = get(finalRes, "GETStats.objectsPerSec", 0);
const putThroughput = get(finalRes, "PUTStats.throughputPerSec", 0);
const putObjects = get(finalRes, "PUTStats.objectsPerSec", 0);
let statJoin: IndvServerMetric[] = [];
getServers.forEach((item) => {
const hostName = item.endpoint;
const putMetric = putServers.find((item) => item.endpoint === hostName);
let itemJoin: IndvServerMetric = {
getUnit: "-",
getValue: "N/A",
host: item.endpoint,
putUnit: "-",
putValue: "N/A",
};
if (item.err && item.err !== "") {
itemJoin.getError = item.err;
itemJoin.getUnit = "-";
itemJoin.getValue = "N/A";
} else {
const niceGet = calculateBytes(item.throughputPerSec.toString());
itemJoin.getUnit = niceGet.unit;
itemJoin.getValue = niceGet.total.toString();
}
if (putMetric) {
if (putMetric.err && putMetric.err !== "") {
itemJoin.putError = putMetric.err;
itemJoin.putUnit = "-";
itemJoin.putValue = "N/A";
} else {
const nicePut = calculateBytes(putMetric.throughputPerSec.toString());
itemJoin.putUnit = nicePut.unit;
itemJoin.putValue = nicePut.total.toString();
}
}
statJoin.push(itemJoin);
});
const downloadResults = () => {
const date = new Date();
let element = document.createElement("a");
element.setAttribute(
"href",
"data:text/plain;charset=utf-8," + JSON.stringify(finalRes)
);
element.setAttribute(
"download",
`speedtest_results-${date.toISOString()}.log`
);
element.style.display = "none";
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
};
const toggleJSONView = () => {
setJsonView(!jsonView);
};
const finalResJSON = finalRes ? JSON.stringify(finalRes, null, 4) : "";
const clnMetrics = cleanMetrics(results);
return (
<Fragment>
<Grid container className={classes.objectGeneral}>
<Grid item xs={12} md={6} lg={6}>
<Grid container className={classes.objectGeneral}>
<Grid item xs={12} md={6} lg={6}>
<SpeedTestUnit
icon={
<div className={classes.download}>
<DownloadStatIcon />
</div>
}
title={"GET"}
throughput={getThroughput}
objects={getObjects}
/>
</Grid>
<Grid item xs={12} md={6} lg={6}>
<SpeedTestUnit
icon={
<div className={classes.upload}>
<UploadStatIcon />
</div>
}
title={"PUT"}
throughput={putThroughput}
objects={putObjects}
/>
</Grid>
</Grid>
</Grid>
<Grid item xs={12} md={6} lg={6}>
<ResponsiveContainer width="99%">
<AreaChart data={clnMetrics}>
<defs>
<linearGradient id="colorPut" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#2781B0" stopOpacity={0.9} />
<stop offset="95%" stopColor="#fff" stopOpacity={0} />
</linearGradient>
<linearGradient id="colorGet" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#4CCB92" stopOpacity={0.9} />
<stop offset="95%" stopColor="#fff" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid
strokeDasharray={"0 0"}
strokeWidth={1}
strokeOpacity={0.5}
stroke={"#F1F1F1"}
vertical={false}
/>
<Area
type="monotone"
dataKey={"get"}
stroke={"#4CCB92"}
fill={"url(#colorGet)"}
fillOpacity={0.3}
strokeWidth={2}
dot={false}
/>
<Area
type="monotone"
dataKey={"put"}
stroke={"#2781B0"}
fill={"url(#colorPut)"}
fillOpacity={0.3}
strokeWidth={2}
dot={false}
/>
</AreaChart>
</ResponsiveContainer>
</Grid>
</Grid>
<br />
{clnMetrics.length > 1 && (
<Fragment>
<Grid container>
<Grid item xs={12} md={6} className={classes.descriptorLabel}>
{start ? (
<Fragment>Preliminar Results:</Fragment>
) : (
<Fragment>
{jsonView ? "JSON Results:" : "Detailed Results:"}
</Fragment>
)}
</Grid>
<Grid item xs={12} md={6} className={classes.actionButtons}>
{!start && (
<Fragment>
<BoxIconButton
aria-label="Download"
onClick={downloadResults}
size="large"
>
<DownloadIcon />
</BoxIconButton>
<BoxIconButton
aria-label="Download"
onClick={toggleJSONView}
size="large"
>
<JSONIcon />
</BoxIconButton>
</Fragment>
)}
</Grid>
</Grid>
<Grid container className={classes.resultsContainer}>
{jsonView ? (
<Fragment>
<CodeMirrorWrapper
value={finalResJSON}
readOnly
onBeforeChange={() => {}}
/>
</Fragment>
) : (
<Fragment>
<Grid
item
xs={12}
sm={12}
md={1}
lg={1}
className={classes.resultsIcon}
alignItems={"flex-end"}
>
<ComputerLineIcon width={45} />
</Grid>
<Grid
item
xs={12}
sm={6}
md={3}
lg={2}
className={classes.detailedItem}
>
Nodes: <strong>{finalRes.servers}</strong>
</Grid>
<Grid
item
xs={12}
sm={6}
md={3}
lg={2}
className={classes.detailedItem}
>
Drives: <strong>{finalRes.disks}</strong>
</Grid>
<Grid
item
xs={12}
sm={6}
md={3}
lg={2}
className={classes.detailedItem}
>
Concurrent: <strong>{finalRes.concurrent}</strong>
</Grid>
<Grid
item
xs={12}
sm={12}
md={12}
lg={5}
className={classes.detailedVersion}
>
<span className={classes.versionIcon}>
<VersionIcon />
</span>{" "}
MinIO VERSION <strong>{finalRes.version}</strong>
</Grid>
<Grid item xs={12} className={classes.tableOverflow}>
<table
className={classes.serversTable}
cellSpacing={0}
cellPadding={0}
>
<thead>
<tr>
<th colSpan={2}>Servers</th>
<th>GET</th>
<th>PUT</th>
</tr>
</thead>
<tbody>
{statJoin.map((stats, index) => (
<tr key={`storage-${index.toString()}`}>
<td className={classes.serverIcon}>
<StorageIcon />
</td>
<td className={classes.serverHost}>{stats.host}</td>
{stats.getError && stats.getError !== "" ? (
<td>{stats.getError}</td>
) : (
<Fragment>
<td className={classes.serverValue}>
{prettyNumber(parseFloat(stats.getValue))}
{stats.getUnit}/s.
</td>
</Fragment>
)}
{stats.putError && stats.putError !== "" ? (
<td>{stats.putError}</td>
) : (
<Fragment>
<td className={classes.serverValue}>
{prettyNumber(parseFloat(stats.putValue))}
{stats.putUnit}/s.
</td>
</Fragment>
)}
</tr>
))}
</tbody>
</table>
</Grid>
</Fragment>
)}
</Grid>
</Fragment>
)}
</Fragment>
);
}
Example #27
Source File: LinearGraphWidget.tsx From console with GNU Affero General Public License v3.0 | 4 votes |
LinearGraphWidget = ({
classes,
title,
timeStart,
timeEnd,
propLoading,
panelItem,
apiPrefix,
hideYAxis = false,
areaWidget = false,
yAxisFormatter = (item: string) => item,
xAxisFormatter = (item: string) => item,
zoomActivated = false,
}: ILinearGraphWidget) => {
const dispatch = useDispatch();
const [loading, setLoading] = useState<boolean>(true);
const [data, setData] = useState<object[]>([]);
const [dataMax, setDataMax] = useState<number>(0);
const [result, setResult] = useState<IDashboardPanel | null>(null);
useEffect(() => {
if (propLoading) {
setLoading(true);
}
}, [propLoading]);
useEffect(() => {
if (loading) {
let stepCalc = 0;
if (timeStart !== null && timeEnd !== null) {
const secondsInPeriod = timeEnd.unix() - timeStart.unix();
const periods = Math.floor(secondsInPeriod / 60);
stepCalc = periods < 1 ? 15 : periods;
}
api
.invoke(
"GET",
`/api/v1/${apiPrefix}/info/widgets/${
panelItem.id
}/?step=${stepCalc}&${
timeStart !== null ? `&start=${timeStart.unix()}` : ""
}${timeStart !== null && timeEnd !== null ? "&" : ""}${
timeEnd !== null ? `end=${timeEnd.unix()}` : ""
}`
)
.then((res: any) => {
const widgetsWithValue = widgetDetailsToPanel(res, panelItem);
setData(widgetsWithValue.data);
setResult(widgetsWithValue);
setLoading(false);
let maxVal = 0;
for (const dp of widgetsWithValue.data) {
for (const key in dp) {
if (key === "name") {
continue;
}
let val = parseInt(dp[key]);
if (isNaN(val)) {
val = 0;
}
if (maxVal < val) {
maxVal = val;
}
}
}
setDataMax(maxVal);
})
.catch((err: ErrorResponseHandler) => {
dispatch(setErrorSnackMessage(err));
setLoading(false);
});
}
}, [loading, panelItem, timeEnd, timeStart, dispatch, apiPrefix]);
let intervalCount = Math.floor(data.length / 5);
const linearConfiguration = result
? (result?.widgetConfiguration as ILinearGraphConfiguration[])
: [];
const CustomizedDot = (prop: any) => {
const { cx, cy, index } = prop;
if (index % 3 !== 0) {
return null;
}
return <circle cx={cx} cy={cy} r={3} strokeWidth={0} fill="#07264A" />;
};
const theme = useTheme();
const biggerThanMd = useMediaQuery(theme.breakpoints.up("md"));
return (
<Box className={zoomActivated ? "" : classes.singleValueContainer}>
{!zoomActivated && (
<div className={classes.titleContainer}>
{title} <ExpandGraphLink panelItem={panelItem} />
</div>
)}
<Box
sx={
zoomActivated
? { flexDirection: "column" }
: {
height: "100%",
display: "grid",
gridTemplateColumns: {
md: "1fr 1fr",
sm: "1fr",
},
}
}
style={areaWidget ? { gridTemplateColumns: "1fr" } : {}}
>
{loading && <Loader className={classes.loadingAlign} />}
{!loading && (
<React.Fragment>
<div
className={
zoomActivated ? classes.zoomChartCont : classes.chartCont
}
>
<ResponsiveContainer width="99%">
<AreaChart
data={data}
margin={{
top: 5,
right: 20,
left: hideYAxis ? 20 : 5,
bottom: 0,
}}
>
{areaWidget && (
<defs>
<linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#2781B0" stopOpacity={1} />
<stop
offset="100%"
stopColor="#ffffff"
stopOpacity={0}
/>
<stop
offset="95%"
stopColor="#ffffff"
stopOpacity={0.8}
/>
</linearGradient>
</defs>
)}
<CartesianGrid
strokeDasharray={areaWidget ? "2 2" : "5 5"}
strokeWidth={1}
strokeOpacity={1}
stroke={"#eee0e0"}
vertical={!areaWidget}
/>
<XAxis
dataKey="name"
tickFormatter={(value: any) => xAxisFormatter(value)}
interval={intervalCount}
tick={{
fontSize: "68%",
fontWeight: "normal",
color: "#404143",
}}
tickCount={10}
stroke={"#082045"}
/>
<YAxis
type={"number"}
domain={[0, dataMax * 1.1]}
hide={hideYAxis}
tickFormatter={(value: any) => yAxisFormatter(value)}
tick={{
fontSize: "68%",
fontWeight: "normal",
color: "#404143",
}}
stroke={"#082045"}
/>
{linearConfiguration.map((section, index) => {
return (
<Area
key={`area-${section.dataKey}-${index.toString()}`}
type="monotone"
dataKey={section.dataKey}
isAnimationActive={false}
stroke={!areaWidget ? section.lineColor : "#D7E5F8"}
fill={areaWidget ? "url(#colorUv)" : section.fillColor}
fillOpacity={areaWidget ? 0.65 : 0}
strokeWidth={!areaWidget ? 3 : 0}
strokeLinecap={"round"}
dot={areaWidget ? <CustomizedDot /> : false}
/>
);
})}
<Tooltip
content={
<LineChartTooltip
linearConfiguration={linearConfiguration}
yAxisFormatter={yAxisFormatter}
/>
}
wrapperStyle={{
zIndex: 5000,
}}
/>
</AreaChart>
</ResponsiveContainer>
</div>
{!areaWidget && (
<Fragment>
{zoomActivated && (
<Fragment>
<strong>Series</strong>
<br />
<br />
</Fragment>
)}
{biggerThanMd && (
<div className={classes.legendChart}>
{linearConfiguration.map((section, index) => {
return (
<div
className={classes.singleLegendContainer}
key={`legend-${section.keyLabel}-${index.toString()}`}
>
<div
className={classes.colorContainer}
style={{ backgroundColor: section.lineColor }}
/>
<div className={classes.legendLabel}>
{section.keyLabel}
</div>
</div>
);
})}
</div>
)}
</Fragment>
)}
</React.Fragment>
)}
</Box>
</Box>
);
}
Example #28
Source File: index.tsx From livepeer-com with MIT License | 4 votes |
Chart = ({
data,
multiData,
}: {
data: Array<{ name: number; "Session bitrate": number }>;
multiData?: Array<{
[name: string]: number;
}>;
}) => {
const multistreamNames =
multiData && multiData[0] && Object.keys(multiData[0]);
return (
<Box
css={{
width: "100%",
position: "relative",
".recharts-cartesian-axis-tick": {
fontSize: "$2",
},
}}>
<Text
variant="gray"
size="1"
css={{
transform: "rotate(-90deg)",
position: "absolute",
left: "-70px",
bottom: "70px",
}}>
kbps (multiplied by 1000)
</Text>
<Text
variant="gray"
size="1"
css={{
position: "absolute",
bottom: "-30px",
left: "50px",
}}>
Seconds since stream loaded
</Text>
<ResponsiveContainer width="99%" height={300}>
<LineChart>
<XAxis
type="number"
dataKey="name"
domain={[
data[0]?.name,
data.length < 2 ? 10 : data[data.length - 1].name,
]}
tickCount={7}
allowDataOverflow
/>
<YAxis domain={[0, 1600]} />
<CartesianGrid vertical={false} />
<Tooltip content={<CustomTooltip />} />
<Legend wrapperStyle={{ fontSize: "10px" }} />
<Line
data={data}
cursor="pointer"
type="monotone"
dataKey="Session bitrate"
stroke="#5746AF"
strokeWidth="2px"
/>
{multistreamNames?.map((item, index) => {
if (item !== "name")
return (
<Line
data={multiData}
cursor="pointer"
type="monotone"
dataKey={item}
stroke={getMultistreamColor(index)}
strokeWidth="2px"
/>
);
})}
</LineChart>
</ResponsiveContainer>
</Box>
);
}
Example #29
Source File: Profile.tsx From avalon.ist with MIT License | 4 votes |
render() {
const { initialHeight } = this;
const {
myname,
style: { themeLight },
} = this.props.match.params;
const theme = themeLight ? 'light' : 'dark';
const data: any[] = [];
// const { avatarStyle } = this.props.match.params.style;
const {
username,
nationality,
bio,
gameRating,
gameHistory,
games,
gameStats,
gameShots,
avatars,
showSpy,
redirect,
} = this.state;
for (const k in gameStats) {
const stat = gameStats[k];
data.push({
name: k.charAt(0).toUpperCase() + k.slice(1),
wins: stat[0],
total: stat[1],
Winrate: stat[1] === 0 ? 0 : Percent(stat[0] / stat[1]),
color: SPY_ROLES.has(k) ? '#ff6384' : '#36a2eb',
});
}
const country = countries.find((c) => c.text === nationality);
const totalWon = games[0];
const totalLost = games[1] - totalWon;
const winRate = games[1] > 0 ? Percent(totalWon / games[1]) : 0;
const shotRate = gameShots[1] > 0 ? Percent(gameShots[0] / gameShots[1]) : 0;
let countryFlag = <img alt={'UN'} src={UN_FLAG} />;
if (country && country.value != 'UN') {
if (country.value == 'LGBT') {
countryFlag = <img alt={'Stonewall'} src={STONEWALL_FLAG} />;
} else {
countryFlag = <Flag code={country.value} />;
}
}
return redirect ? (
<Redirect to="/profile-not-found" />
) : (
<div id="Background-2" className={`full ${theme}`}>
<Navbar username="" key={'Navbar'} />
<AvalonScrollbars>
<div id="Profile" style={{ minHeight: `${initialHeight}px` }}>
<div className="row">
<div id="user">
<img
src={showSpy ? avatars.spy : avatars.res}
alt={'Avatar'}
onMouseOver={this.onHover}
onMouseLeave={this.onStopHover}
/>
<div className="user-tag">
{countryFlag}
<p>
<b>{username}</b>
<br />
{nationality}
</p>
</div>
</div>
<div id="bio" className="bubble">
<AvalonScrollbars>
<ReactMarkdown
className="markdown"
allowedTypes={[
'text',
'paragraph',
'emphasis',
'strong',
'thematicBreak',
'blockquote',
'list',
'listItem',
'heading',
]}
>
{bio}
</ReactMarkdown>
</AvalonScrollbars>
</div>
</div>
<div className="row">
<div id="stats">
<h1>STATISTICS</h1>
<table>
<tbody>
<tr>
<th>Statistic</th>
<th>Value</th>
</tr>
<tr>
<td>Total Games Played</td>
<td>{games[1]}</td>
</tr>
<tr>
<td>Total Games Won</td>
<td>{totalWon}</td>
</tr>
<tr>
<td>Total Games Lost</td>
<td>{totalLost}</td>
</tr>
<tr>
<td>Total Win Rate</td>
<td>{winRate}%</td>
</tr>
<tr>
<td>Shot Accuracy</td>
<td>{shotRate}%</td>
</tr>
<tr>
<td>Rating</td>
<td>{gameRating}</td>
</tr>
</tbody>
</table>
</div>
<div id="graph">
<ResponsiveContainer width={'100%'} height={300}>
<BarChart
layout="vertical"
margin={{
top: 20,
right: 20,
bottom: 20,
left: 20,
}}
data={data}
>
<CartesianGrid strokeDasharray="1 1" />
<XAxis type="number" domain={[0, 100]} />
<YAxis type="category" width={100} dataKey="name" />
<Tooltip content={<CustomTooltip />} />
<Bar dataKey="Winrate" fill="#8884d8">
{data.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
</div>
<div className="row">
<div id="history">
<h1>GAME HISTORY</h1>
<table>
<tbody>
<tr>
<th>Game</th>
<th>Role</th>
<th>Size</th>
<th>Winner</th>
<th>Date</th>
</tr>
{gameHistory
.slice(-10)
.reverse()
.map((g: any, i) => {
const date = new Date(g.date);
const month = ('00' + (date.getUTCMonth() + 1)).slice(-2);
const day = ('00' + date.getUTCDate()).slice(-2);
const year = date.getUTCFullYear();
return (
<tr key={'Game' + g.id}>
<td>
<Link to={'/game/' + g.id}>#{g.code}</Link>
</td>
<td>{g.role}</td>
<td>{g.size}</td>
<td>{g.winner ? 'Resistance' : 'Spy'}</td>
<td>
{year}-{month}-{day}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</div>
</AvalonScrollbars>
{myname === username ? (
<button
className="button-b edit-your-profile-with-this"
type="button"
onClick={this.onFormToggle}
>
<p>Edit Profile</p>
</button>
) : null}
{this.state.showForm ? (
<EditProfile
onExit={this.onFormToggle}
text="Submit"
nationality={nationality}
bio={bio}
title="EDIT YOUR PROFILE"
onSelect={this.onEdit}
/>
) : null}
</div>
);
}