import React, { useMemo, useState } from "react"; import { Bar } from "@visx/shape"; import { Group } from "@visx/group"; import { LinearGradient } from "@visx/gradient"; import { AxisBottom, AxisLeft } from "@visx/axis"; import { scaleBand, scaleLinear } from "@visx/scale"; const verticalMargin = 20; const leftMargin = 50; const barPadding = 4; interface tripPurpose { trip_purpose_group: string; percentage: number; } export type BarsProps = { data: tripPurpose[]; width: number; height: number; events?: boolean; }; const getTripPurposeValue = (d: tripPurpose) => Number(d.percentage); export default function SimpleChartTripPurpose({ data, width, height, events = false, }: BarsProps) { const xMax = width - leftMargin; const yMax = height - verticalMargin - 20; const xScale = useMemo( () => scaleBand({ range: [0, xMax], round: true, domain: data.map((d: any) => d.trip_purpose_group), paddingInner: 0.2, paddingOuter: 0.1, }), [xMax] ); const yScale = useMemo( () => scaleLinear({ range: [yMax, 0], round: true, domain: [0, Math.max(...data.map(getTripPurposeValue))], }), [yMax] ); const [isHover, setIsHover] = useState(Array(data.length).fill(false)); return width < 10 ? null : ( {data.map((d: any, index: any) => { const barWidth = xScale.bandwidth(); const barHeight = yMax - (yScale(d.percentage) ?? 0); const barX = xScale(d.trip_purpose_group) ?? 0; const barY = yMax - barHeight; return ( { if (events) alert(`clicked: ${JSON.stringify(d)}`); }} onMouseMove={() => { const updatedHover = [...isHover]; updatedHover[index] = true; setIsHover(updatedHover); }} onMouseLeave={() => { const updatedHover = [...isHover]; updatedHover[index] = false; setIsHover(updatedHover); }} /> ); })} ({ fill: "white", fontSize: 10, textAnchor: "middle", fontWeight: "bold", })} /> value.toString()} tickStroke="white" strokeWidth={2} stroke="white" tickLabelProps={() => ({ fill: "white", fontSize: 11, textAnchor: "end", dy: "0.3em", dx: "-0.25em", fontWeight: "bold", })} /> ); }