@@ -16,9 +16,11 @@ export function positiveNegativeBarGraph(
16
16
const minValue = d3 . min ( data . map ( ( bm ) => bm . value ) ) ! ;
17
17
const maxValue = d3 . max ( data . map ( ( bm ) => bm . value ) ) ! ;
18
18
19
+ const range = maxValue - minValue ;
20
+
19
21
const yScale = d3
20
22
. scaleLinear ( )
21
- . domain ( [ minValue * 1.2 , maxValue * 1.2 ] )
23
+ . domain ( [ minValue - 0.2 * range , maxValue + 0.2 * range ] )
22
24
. range ( [ 0 , height - 10 ] ) ;
23
25
24
26
const yAxis = d3 . axisLeft ( yScale ) ;
@@ -29,7 +31,7 @@ export function positiveNegativeBarGraph(
29
31
. range ( [ GRAPH_MARGIN . left , width - GRAPH_MARGIN . right ] ) ;
30
32
31
33
const bandWidth = xScale . bandwidth ( ) ;
32
- const barWidth = 25 ;
34
+ const barWidth = Math . min ( 25 , ( 0.5 * width ) / data . length ) ;
33
35
34
36
const xAxis = d3 . axisBottom ( xScale ) ;
35
37
@@ -40,25 +42,27 @@ export function positiveNegativeBarGraph(
40
42
41
43
selection . append ( "g" ) . attr ( "transform" , `translate(${ GRAPH_MARGIN . left } , ${ GRAPH_MARGIN . top } )` ) . call ( yAxis ) ;
42
44
43
- const barSize = ( val : number ) => Math . abs ( height / 2 - yScale ( val ) ! ) ;
45
+ const barSize = ( val : number ) => Math . abs ( yScale ( 0 ) ! - yScale ( val ) ! ) ;
44
46
45
47
const bars = selection . selectAll ( "rect" ) . data ( data ) . enter ( ) ;
46
48
47
49
bars . append ( "rect" )
48
50
. attr ( "width" , barWidth )
49
51
. attr ( "x" , ( d ) => xScale ( d . name ) ! + 0.5 * bandWidth - 0.5 * barWidth )
50
- . attr ( "height" , ( d ) => barSize ( d . value ) - 1 )
51
- . attr ( "y" , ( d ) => ( d . value > 0 ? height / 2 + 10 : height / 2 + 10 - barSize ( d . value ) ) )
52
- . style ( "fill" , ( d ) => ( d . value > 0 ? "red" : "green" ) ) ;
53
- //.style("stroke", "currentColor");
52
+ . attr ( "height" , ( d ) => barSize ( d . value ) )
53
+ . attr ( "y" , ( d ) => GRAPH_MARGIN . top + ( d . value > 0 ? yScale ( 0 ) ! : yScale ( 0 ) ! - barSize ( d . value ) ) )
54
+ . style ( "fill" , ( d ) => ( d . value > 0 ? "red" : "green" ) )
55
+ . style ( "stroke" , "currentColor" )
56
+ // Add hover tooltip
57
+ . append ( "svg:title" )
58
+ . text ( ( d ) => `${ d . name } : ${ d . value . toFixed ( 2 ) } %` ) ;
54
59
55
60
bars . append ( "text" )
56
61
. text ( ( d ) => `${ d . value > 0 ? "+" : "" } ${ d . value . toFixed ( 2 ) } %` )
57
62
. attr ( "x" , ( d ) => xScale ( d . name ) ! + 0.5 * bandWidth )
58
- . attr ( "y" , ( d ) => ( d . value > 0 ? height / 2 + barSize ( d . value ) + 30 : height / 2 - barSize ( d . value ) ) )
63
+ . attr ( "y" , ( d ) => ( d . value > 0 ? Math . max ( yScale ( 0 ) ! + 40 , yScale ( d . value ) ! + 20 ) : yScale ( d . value ) ! ) )
59
64
. style ( "fill" , "currentColor" )
60
65
. style ( "text-anchor" , "middle" ) ;
61
- //.style("stroke", "currentColor");
62
66
63
67
return selection ;
64
68
}
0 commit comments