@@ -16,9 +16,11 @@ export function positiveNegativeBarGraph(
1616 const minValue = d3 . min ( data . map ( ( bm ) => bm . value ) ) ! ;
1717 const maxValue = d3 . max ( data . map ( ( bm ) => bm . value ) ) ! ;
1818
19+ const range = maxValue - minValue ;
20+
1921 const yScale = d3
2022 . scaleLinear ( )
21- . domain ( [ minValue * 1.2 , maxValue * 1.2 ] )
23+ . domain ( [ minValue - 0.2 * range , maxValue + 0.2 * range ] )
2224 . range ( [ 0 , height - 10 ] ) ;
2325
2426 const yAxis = d3 . axisLeft ( yScale ) ;
@@ -29,7 +31,7 @@ export function positiveNegativeBarGraph(
2931 . range ( [ GRAPH_MARGIN . left , width - GRAPH_MARGIN . right ] ) ;
3032
3133 const bandWidth = xScale . bandwidth ( ) ;
32- const barWidth = 25 ;
34+ const barWidth = Math . min ( 25 , ( 0.5 * width ) / data . length ) ;
3335
3436 const xAxis = d3 . axisBottom ( xScale ) ;
3537
@@ -40,25 +42,27 @@ export function positiveNegativeBarGraph(
4042
4143 selection . append ( "g" ) . attr ( "transform" , `translate(${ GRAPH_MARGIN . left } , ${ GRAPH_MARGIN . top } )` ) . call ( yAxis ) ;
4244
43- const barSize = ( val : number ) => Math . abs ( height / 2 - yScale ( val ) ! ) ;
45+ const barSize = ( val : number ) => Math . abs ( yScale ( 0 ) ! - yScale ( val ) ! ) ;
4446
4547 const bars = selection . selectAll ( "rect" ) . data ( data ) . enter ( ) ;
4648
4749 bars . append ( "rect" )
4850 . attr ( "width" , barWidth )
4951 . 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 ) } %` ) ;
5459
5560 bars . append ( "text" )
5661 . text ( ( d ) => `${ d . value > 0 ? "+" : "" } ${ d . value . toFixed ( 2 ) } %` )
5762 . 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 ) ! ) )
5964 . style ( "fill" , "currentColor" )
6065 . style ( "text-anchor" , "middle" ) ;
61- //.style("stroke", "currentColor");
6266
6367 return selection ;
6468}
0 commit comments