Using time scale for bar and line charts #1566
Replies: 4 comments
-
Hey @umarluqman 👋 thanks for checking out if you use a if you use a |
Beta Was this translation helpful? Give feedback.
-
Thanks for the reply @williaster , I would like to use the |
Beta Was this translation helpful? Give feedback.
-
i would also like to use a time scale for the axis and a band scale for the buckets themselves. currently, i am hand-coding this using the d3-scales and the |
Beta Was this translation helpful? Give feedback.
-
Using the The common factor in these cases are when the time interval is different for each bar. In other words, the problem happens when the spacing between each bar has to be different. For Here is a sample code for the const StackedBarChart: FC<Props> = ({
width,
height,
data = mockData,
colors = ['#6c5efb', '#c998ff', '#a44afe'],
}) => {
const xScale = scaleTime({
domain: extent(data.map((d) => new Date(d.date))) as [Date, Date],
range: [0, width],
});
const yScale = scaleLinear<number>({
domain: [
0,
Math.max(
...data
.map((d) =>
Object.values(d.data).reduce(
(acc, curr) => Number(acc) + Number(curr),
0,
),
)
.flat(),
),
],
range: [height, 0],
});
const keys = Object.keys(data[0]?.data);
const colorScale = scaleOrdinal<string, string>({
domain: keys,
range: colors,
});
return (
<svg width={width} height={height}>
<Group left={30}>
<AxisLeft scale={yScale} />
<AxisBottom scale={xScale} top={height} />
</Group>
<Group left={150}>
<BarStack
data={data.map((d) => ({ ...d.data, date: d.date }))}
keys={keys}
xScale={xScale}
yScale={yScale}
color={colorScale}
x={(d) => new Date(d.date)}
>
{(barStacks) => {
return barStacks.map((barStack) =>
barStack.bars.map((bar) => (
<rect
key={`bar-stack-${barStack.index}-${bar.index}`}
x={bar.x}
y={bar.y}
height={bar.height}
width={width / data.length}
fill={bar.color}
/>
)),
);
}}
</BarStack>
</Group>
</svg>
);
}; |
Beta Was this translation helpful? Give feedback.
-
I wonder is it possible to use time scale in x-axis like the image above? I knew it works well with the line but I'm not sure about using time scale for the bar.
Beta Was this translation helpful? Give feedback.
All reactions