I have below piece of code. I am using React and svg for bar charts. I am not using any third party library for charts. With this below piece of code, i am able to get the bar charts. But the issue is that my bar charts show horizontally, I want to show it vertically. I am not able to figure out how to get this same piece of code working for a vertical bar chart.
I saw one video online https://egghead.io/lessons/javascript-build-a-bar-chart-with-svg-from-scratch-with-react This guy is able to achieve the bar chart vertically. I am not sure where i am going wrong in displaying it. Any changes i do or try, it always show horizontal bar chart.
JavaScript
x
81
81
1
export const ReleaseScopeCharts = () => {
2
const data = [
3
{
4
"name": "Transit",
5
"passed": 2,
6
"skipped": 5,
7
"failed": 22,
8
},
9
{
10
"name": "Access",
11
"passed": 7,
12
"skipped": 2,
13
"failed": 11,
14
}
15
]
16
const fontSize=14
17
const width=1000
18
const rowHeight=40
19
const colors = ["#30D158", "#005EA7", "#FF453A"];
20
21
const entries = data.map((d) => ({
22
name: d.name,
23
total: d.total,
24
bars: ["passed", "skipped", "failed"].map((key, i) => ({
25
value: d[key],
26
portion: d[key] / 29,
27
color: colors[i]
28
}))
29
.filter((bar) => bar.value)
30
}))
31
const heightPerRow = rowHeight;
32
const canvasHeight = entries.length * heightPerRow;
33
const canvasWidth = width;
34
const labelWidth = canvasWidth / 4;
35
const plotWidth = canvasWidth - labelWidth;
36
const verticalPadding = heightPerRow / 2;
37
const barHeight = heightPerRow - verticalPadding;
38
const horizontalPadding = 0;
39
const rows = entries.map((entry, i) => {
40
const widths = entry.bars.map((bar) => plotWidth * bar.portion)
41
const offsets = entry.bars.map((bar, i, array) => {
42
const previous = array.slice(0, i);
43
const offset = previous.map((bar) => bar.portion)
44
.reduce((a, b) => a + b, 0)
45
46
return offset + bar.portion / 2
47
})
48
49
const bars = entry.bars.map((bar, i) => {
50
const barWidth = widths[i] - horizontalPadding;
51
return (<g key={i} transform={`translate(${plotWidth * offsets[i]}, ${heightPerRow / 2})`}>
52
<rect
53
rx={barHeight / 2} ry={barHeight / 2} width={barWidth} height={barHeight} fill={bar.color} x={-barWidth / 2} y={-barHeight / 2} />
54
<text fill={"#fff"} fontSize={fontSize} textAnchor={"middle"} alignmentBaseline={"middle"}>{bar.value}</text>
55
</g>)
56
})
57
return (
58
<g key={i} transform={`translate(${labelWidth},${heightPerRow * i})`}>
59
<g transform={`translate(${-labelWidth}, ${heightPerRow / 2})`}>
60
<text
61
fontSize={fontSize}
62
textAnchor={"start"}
63
alignmentBaseline={"middle"}>{entry.name}</text>
64
</g>
65
{bars}
66
</g>
67
)
68
})
69
return (
70
<div className="new-card">
71
<div>
72
</div>
73
<svg viewBox={`0, 0, ${canvasWidth}, ${canvasHeight}`}
74
height={canvasHeight}
75
width={canvasWidth}
76
>
77
{rows}
78
</svg>
79
</div>
80
)}
81
Can someone please help me figure out where i went wrong.