@@ -6,8 +6,10 @@ export function getAxes(
66 margin : { top : number ; right : number ; bottom : number ; left : number } ,
77 size : { x : number ; y : number }
88) {
9- const xScale = ( value : number ) => ( value * ( width - margin . left - margin . right ) ) / size . x + margin . left
10- const yScale = ( value : number ) => height - margin . bottom - ( value / size . y ) * ( height - margin . top - margin . bottom )
9+ // +/- 1 is to avoid overlapping axis lines
10+ const xScale = ( value : number ) => ( value * ( width - margin . left - margin . right ) ) / size . x + margin . left + 1
11+ const yScale = ( value : number ) =>
12+ height - margin . bottom - ( value / size . y ) * ( height - margin . top - margin . bottom ) - 1
1113 const innerWidth = width - margin . left - margin . right
1214 const innerHeight = height - margin . top - margin . bottom
1315 return { xScale, yScale, innerWidth, innerHeight }
@@ -56,7 +58,9 @@ export function drawXAxis(
5658 context . lineTo ( xPos , height - margin . bottom + 6 )
5759 context . stroke ( )
5860 context . fillStyle = options . textColor ?? 'black'
59- context . fillText ( Math . round ( range . min + i * labelGap ) . toString ( ) , xPos - 3 , height )
61+ const label = Math . round ( range . min + i * labelGap ) . toString ( )
62+ const textWidth = context . measureText ( label ) . width
63+ context . fillText ( label , xPos - textWidth / 2 , height )
6064 }
6165 }
6266}
@@ -82,7 +86,9 @@ export function drawYAxis(
8286 context . lineTo ( margin . left - 6 , yPos )
8387 context . stroke ( )
8488 context . fillStyle = options . textColor ?? 'black'
85- context . fillText ( point . toString ( ) , 0 , yPos + 5 )
89+ const label = point . toString ( )
90+ const textWidth = context . measureText ( label ) . width
91+ context . fillText ( label , margin . left - textWidth - 10 , yPos + 5 )
8692 }
8793 } else if ( options . count ) {
8894 const gap = ( range . max - range . min ) / ( options . count - ( options . centered ? 0 : 1 ) )
@@ -94,7 +100,9 @@ export function drawYAxis(
94100 context . lineTo ( margin . left - 6 , yPos )
95101 context . stroke ( )
96102 context . fillStyle = options . textColor ?? 'black'
97- context . fillText ( Math . round ( range . min + i * labelGap ) . toString ( ) , 0 , yPos + 5 )
103+ const label = Math . round ( range . min + i * labelGap ) . toString ( )
104+ const textWidth = context . measureText ( label ) . width
105+ context . fillText ( label , margin . left - textWidth - 10 , yPos + 5 )
98106 }
99107 }
100108}
0 commit comments