Przeglądaj źródła

Abbreviate Y axis tick values

Fela Maslen 5 lat temu
rodzic
commit
f8d67f9748
1 zmienionych plików z 34 dodań i 2 usunięć
  1. 34 2
      src/components/graph-cases.tsx

+ 34 - 2
src/components/graph-cases.tsx

@@ -35,7 +35,33 @@ const Key = styled.ul`
 `;
 
 const dateTickFormatter = (date: Date): string => {
-  return format(new Date(date), 'LLL do'); // 'Do MMM');
+  return format(new Date(date), 'LLL do');
+};
+
+const superscript: { [k: string]: string } = {
+  0: '\u2070',
+  1: '\u00b9',
+  2: '\u00b2',
+  3: '\u00b3',
+  4: '\u2074',
+  5: '\u2075',
+  6: '\u2076',
+  7: '\u2077',
+  8: '\u2078',
+  9: '\u2079',
+};
+
+const yTickFormatter = (value: number): string => {
+  if (value.toFixed().length < 7) {
+    return String(value);
+  }
+
+  const exp = Math.floor(Math.log10(value));
+  const num = (value / 10 ** exp).toFixed(1);
+  const valueAbbr = num === '1.0' ? '' : `${num}x`;
+  const expAbbr = exp in superscript ? `10${superscript[exp]}` : `10^${exp}`;
+
+  return `${valueAbbr}${expAbbr}`;
 };
 
 type Props = {
@@ -118,7 +144,13 @@ const GraphCases: React.FC<Props> = ({ countries }) => {
           tickFormatter={dateTickFormatter}
           type="number"
         />
-        <YAxis scale={scale} tick yAxisId="left" domain={[50, 'auto']} />
+        <YAxis
+          scale={scale}
+          tick
+          yAxisId="left"
+          domain={[50, 'auto']}
+          tickFormatter={yTickFormatter}
+        />
         <CartesianGrid stroke="#f5f5f5" />
         {enabledCountries.map(({ country, color }) => (
           <Line