All files / owid-grapher/grapher/scatterCharts ScatterPlotChart.tsx

85.55% Statements 722/844
74.65% Branches 106/142
84% Functions 63/75
85.55% Lines 722/844

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 9711x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x         4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x                                 200x         4x 4x 4x 4x 4x 4x 4x 4x               4x 4x                         4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 90x 90x 4x 4x 90x 90x 90x 90x 90x 4x 4x 4x 90x 90x 90x 1x 1x 90x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 90x 90x 90x 1x 1x 90x 11x 11x 11x 11x 11x 90x 90x 4x 4x 4x 4x 4x 4x 8x 8x 4x 4x         4x 4x 11x 11x 4x 4x     4x 4x 4x 4x 7x 7x 6x 6x 7x 7x 7x 6x 7x 7x 7x 7x 7x 7x 7x 7x 4x 4x 18x 18x 4x 4x     4x 4x     4x 4x 4x                                     4x 4x 4x 15x 15x 1x 1x 1x 1x 1x 1x 1x 1x 15x 4x 4x 4x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 4x 4x 1x 1x 4x 4x 15x 15x 15x 15x 4x 4x 15x 15x 15x 15x 4x 4x 15x 15x 4x 15x 15x 4x 4x 4x 4x 4x     4x 4x     4x 4x     4x 4x 15x 15x 15x 15x 15x 15x 15x 15x 15x 4x 4x 8x 8x 4x 4x 1x 1x 4x 4x 8x 8x 4x 4x 8x 8x 4x 4x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 8x 8x 8x 8x 8x 8x 8x 4x 4x     4x 4x     4x 4x 15x 15x 15x 15x 4x 4x       4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 15x 15x 4x 4x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 4x 4x 4x 4x 4x 4x 78x 78x 4x 4x 9x 9x 9x 9x 4x 4x 8x 8x 4x 4x 15x 15x 4x 4x 15x 15x   15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 7x 7x 15x 15x 15x 15x 15x 15x 15x 15x 4x 15x 15x 15x 15x 15x 15x 15x 15x 4x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 4x 4x 15x 15x 4x 4x 15x 15x 4x 4x 4x 4x 49x 49x 49x 49x 49x 4x 4x 63x 63x 63x 63x 63x 4x 4x 4x 4x 4x 52x 49x 49x 49x 49x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 41x 41x 4x 4x 4x 4x 4x 4x 4x 40x 40x 4x 4x 4x 4x 4x 4x 39x 39x 4x 4x 3x 2x 2x 2x 3x                   2x 3x 2x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 3x 3x 3x 3x 3x 4x 4x 4x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 90x 90x 4x 4x 22x 22x 4x 4x 4x 16x 16x 16x 16x 16x 16x   16x 16x 16x                   4x 4x 8x 8x 4x 4x           4x 4x 8x 8x 2x 8x 8x     8x 4x 4x 15x 2x 2x 2x 2x 2x 4x 4x 4x   4x 4x 4x 4x 8x 8x 4x 4x 8x 8x 8x 8x 8x 8x 8x 8x 8x 6x 6x         8x 2x 2x 2x 8x 8x 8x 4x 4x 4x   4x 4x 4x 4x 8x                                                                                                                                                                                                                                                              
import * as React from "react"
import { ComparisonLineConfig } from "../scatterCharts/ComparisonLine"
import { observable, computed, action } from "mobx"
import {
    intersection,
    without,
    uniq,
    last,
    excludeUndefined,
    flatten,
    isEmpty,
    isNumber,
    domainExtent,
    lowerCaseFirstLetterUnlessAbbreviation,
    relativeMinAndMax,
    exposeInstanceOnWindow,
    groupBy,
    sampleFrom,
    intersectionOfSets,
} from "../../clientUtils/Util"
import { observer } from "mobx-react"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import { NoDataModal } from "../noDataModal/NoDataModal"
import {
    BASE_FONT_SIZE,
    ScaleType,
    EntitySelectionMode,
    ScatterPointLabelStrategy,
    SeriesName,
} from "../core/GrapherConstants"
import { Color } from "../../coreTable/CoreTableConstants"
import {
    ConnectedScatterLegend,
    ConnectedScatterLegendManager,
} from "./ConnectedScatterLegend"
import {
    VerticalColorLegend,
    VerticalColorLegendManager,
} from "../verticalColorLegend/VerticalColorLegend"
import { DualAxisComponent } from "../axis/AxisViews"
import { DualAxis, HorizontalAxis, VerticalAxis } from "../axis/Axis"
import { ComparisonLine } from "./ComparisonLine"
 
import { ColorScale, ColorScaleManager } from "../color/ColorScale"
import { AxisConfig } from "../axis/AxisConfig"
import { ChartInterface } from "../chart/ChartInterface"
import {
    ScatterPlotManager,
    ScatterSeries,
    SeriesPoint,
} from "./ScatterPlotChartConstants"
import { ScatterTooltip } from "./ScatterTooltip"
import { ScatterPointsWithLabels } from "./ScatterPointsWithLabels"
import {
    EntityName,
    OwidRow,
    OwidTableSlugs,
} from "../../coreTable/OwidTableConstants"
import { OwidTable } from "../../coreTable/OwidTable"
import { autoDetectYColumnSlugs, makeSelectionArray } from "../chart/ChartUtils"
import { ColorSchemeName } from "../color/ColorConstants"
import {
    defaultIfErrorValue,
    isNotErrorValue,
} from "../../coreTable/ErrorValues"
import {
    ColorScaleConfig,
    ColorScaleConfigDefaults,
} from "../color/ColorScaleConfig"
import { SelectionArray } from "../selection/SelectionArray"
import { CoreColumn } from "../../coreTable/CoreTableColumns"
import { ColorScaleBin } from "../color/ColorScaleBin"
 
@observer
export class ScatterPlotChart
    extends React.Component<{
        bounds?: Bounds
        manager: ScatterPlotManager
    }>
    implements
        ConnectedScatterLegendManager,
        ChartInterface,
        VerticalColorLegendManager,
        ColorScaleManager
{
    // currently hovered individual series key
    @observable private hoveredSeries?: SeriesName
    // currently hovered legend color
    @observable private hoverColor?: Color
 
    transformTable(table: OwidTable): OwidTable {
        const { backgroundSeriesLimit, excludedEntities, addCountryMode } =
            this.manager
 
        if (
            addCountryMode === EntitySelectionMode.Disabled ||
            addCountryMode === EntitySelectionMode.SingleEntity
        ) {
            table = table.filterByEntityNames(
                this.selectionArray.selectedEntityNames
            )
        }
 
        if (excludedEntities) {
            const excludedEntityIdsSet = new Set(excludedEntities)
            table = table.columnFilter(
                OwidTableSlugs.entityId,
                (entityId) => !excludedEntityIdsSet.has(entityId as number),
                `Excluded entity ids specified by author: ${excludedEntities.join(
                    ", "
                )}`
            )
        }
 
        // Allow authors to limit the # of background entities to get better perf and clearer charts.
        if (backgroundSeriesLimit) {
            const selectedSeriesNames = new Set<SeriesName>(
                this.selectionArray.selectedEntityNames
            )
            // Todo: implement a better strategy for picking the entities to show for context. Maybe a couple per decile?
            const backgroundSeriesNames = new Set<SeriesName>(
                sampleFrom(
                    table.availableEntityNames.filter(
                        (name) => !selectedSeriesNames.has(name)
                    ),
                    backgroundSeriesLimit,
                    123
                )
            )
            table = table.columnFilter(
                table.entityNameSlug,
                (name) =>
                    selectedSeriesNames.has(name as string) ||
                    backgroundSeriesNames.has(name as string),
                `Capped background series at ${backgroundSeriesLimit}`
            )
        }
 
        if (this.xScaleType === ScaleType.log && this.xColumnSlug)
            table = table.replaceNonPositiveCellsForLogScale([this.xColumnSlug])
 
        if (this.yScaleType === ScaleType.log && this.yColumnSlug)
            table = table.replaceNonPositiveCellsForLogScale([this.yColumnSlug])
 
        if (this.sizeColumnSlug) {
            // The tolerance on the size column is ignored. If we want to change this in the future
            // we need to check all charts for regressions.
            table = table.interpolateColumnWithTolerance(
                this.sizeColumnSlug,
                Infinity
            )
        }
 
        if (this.colorColumnSlug) {
            const tolerance =
                table.get(this.colorColumnSlug)?.display?.tolerance ?? Infinity
            table = table.interpolateColumnWithTolerance(
                this.colorColumnSlug,
                tolerance
            )
            if (this.manager.matchingEntitiesOnly) {
                table = table.dropRowsWithErrorValuesForColumn(
                    this.colorColumnSlug
                )
            }
        }
 
        // We want to "chop off" any rows outside the time domain for X and Y to avoid creating
        // leading and trailing timeline times that don't really exist in the dataset.
        const [timeDomainStart, timeDomainEnd] = table.timeDomainFor([
            this.xColumnSlug,
            this.yColumnSlug,
        ])
        table = table.filterByTimeRange(
            timeDomainStart ?? -Infinity,
            timeDomainEnd ?? Infinity
        )
 
        if (this.xOverrideTime !== undefined) {
            table = table.interpolateColumnWithTolerance(this.yColumnSlug)
        } else {
            table = table.interpolateColumnsByClosestTimeMatch(
                this.xColumnSlug,
                this.yColumnSlug
            )
        }
 
        // Drop any rows which have non-number values for X or Y.
        // This needs to be done after the tolerance, because the tolerance may fill in some gaps.
        table = table
            .columnFilter(
                this.xColumnSlug,
                isNumber,
                "Drop rows with non-number values in X column"
            )
            .columnFilter(
                this.yColumnSlug,
                isNumber,
                "Drop rows with non-number values in Y column"
            )
 
        // The tolerance application might lead to some data being dropped for some years.
        // For example, if X times are [2000, 2005, 2010], and Y times are [2005], then for all 3
        // rows we have the same match [[2005, 2005], [2005, 2005], [2005, 2005]].
        // This means we can drop 2000 and 2010 from the timeline.
        // It might not make a huge difference here, but it makes a difference when there are more
        // entities covering different time periods.
        const [originalTimeDomainStart, originalTimeDomainEnd] =
            table.originalTimeDomainFor([this.xColumnSlug, this.yColumnSlug])
        table = table.filterByTimeRange(
            originalTimeDomainStart ?? -Infinity,
            originalTimeDomainEnd ?? Infinity
        )
 
        return table
    }
 
    @computed get inputTable(): OwidTable {
        return this.manager.table
    }
 
    @computed private get transformedTableFromGrapher(): OwidTable {
        return (
            this.manager.transformedTable ??
            this.transformTable(this.inputTable)
        )
    }
 
    // TODO chunk this up into multiple computeds for better performance?
    @computed get transformedTable(): OwidTable {
        let table = this.transformedTableFromGrapher
        if (
            this.manager.hideLinesOutsideTolerance &&
            this.manager.startTime !== undefined &&
            this.manager.endTime !== undefined
        ) {
            const entityNames = Array.from(
                intersectionOfSets(
                    [this.manager.startTime, this.manager.endTime].map(
                        (targetTime) =>
                            table.filterByTargetTimes([targetTime], 0)
                                .availableEntityNameSet
                    )
                )
            )
            table = table.filterByEntityNames(entityNames)
        }
        // We don't want to apply this transform when relative mode is also enabled, it has a
        // sligthly different endpoints logic that drops initial zeroes to avoid DivideByZero error.
        if (this.compareEndPointsOnly && !this.manager.isRelativeMode) {
            table = table.keepMinTimeAndMaxTimeForEachEntityOnly()
        }
        if (this.manager.isRelativeMode) {
            table = table.toAverageAnnualChangeForEachEntity([
                this.xColumnSlug,
                this.yColumnSlug,
            ])
        }
        return table
    }
 
    @computed private get manager(): ScatterPlotManager {
        return this.props.manager
    }
 
    @computed.struct private get bounds(): Bounds {
        return this.props.bounds ?? DEFAULT_BOUNDS
    }
 
    @computed private get canAddCountry(): boolean {
        const { addCountryMode } = this.manager
        return (addCountryMode &&
            addCountryMode !== EntitySelectionMode.Disabled) as boolean
    }
 
    @computed private get selectionArray(): SelectionArray {
        return makeSelectionArray(this.manager)
    }
 
    @action.bound private onSelectEntity(entityName: SeriesName): void {
        if (this.canAddCountry) this.selectionArray.toggleSelection(entityName)
    }
 
    // Returns the colors that are used by all points, *across the whole timeline*.
    // This is why we need the table before the timeline filter is applied.
    @computed private get colorsInUse(): Color[] {
        const allValues =
            this.manager.tableAfterAuthorTimelineAndActiveChartTransformAndPopulationFilter?.get(
                this.colorColumnSlug
            )?.valuesIncludingErrorValues ?? []
        // Need to convert InvalidCell to undefined for color scale to assign correct color
        const colorValues = uniq(
            allValues.map((value) =>
                isNotErrorValue(value) ? value : undefined
            )
        ) as (string | number)[]
        return excludeUndefined(
            colorValues.map((colorValue) =>
                this.colorScale.getColor(colorValue)
            )
        )
    }
 
    @computed get fontSize(): number {
        return this.manager.baseFontSize ?? BASE_FONT_SIZE
    }
 
    @action.bound onLegendMouseOver(color: string): void {
        this.hoverColor = color
    }
 
    @action.bound onLegendMouseLeave(): void {
        this.hoverColor = undefined
    }
 
    // When the color legend is clicked, toggle selection fo all associated keys
    @action.bound onLegendClick(): void {
        const { hoverColor, selectionArray } = this
        if (!this.canAddCountry || hoverColor === undefined) return

        const keysToToggle = this.series
            .filter((g) => g.color === hoverColor)
            .map((g) => g.seriesName)
        const allKeysActive =
            intersection(keysToToggle, this.selectedEntityNames).length ===
            keysToToggle.length
        if (allKeysActive)
            selectionArray.setSelectedEntities(
                without(this.selectedEntityNames, ...keysToToggle)
            )
        else
            selectionArray.setSelectedEntities(
                uniq(this.selectedEntityNames.concat(keysToToggle))
            )
    }
 
    // Colors on the legend for which every matching series is focused
    @computed get focusColors(): string[] {
        const { colorsInUse } = this
        return colorsInUse.filter((color) => {
            const matchingKeys = this.series
                .filter((g) => g.color === color)
                .map((g) => g.seriesName)
            return (
                intersection(matchingKeys, this.selectedEntityNames).length ===
                matchingKeys.length
            )
        })
    }
 
    // All currently hovered series keys, combining the legend and the main UI
    @computed private get hoveredSeriesNames(): string[] {
        const { hoverColor, hoveredSeries } = this
 
        const hoveredSeriesNames =
            hoverColor === undefined
                ? []
                : uniq(
                      this.series
                          .filter((g) => g.color === hoverColor)
                          .map((g) => g.seriesName)
                  )
 
        if (hoveredSeries !== undefined) hoveredSeriesNames.push(hoveredSeries)
 
        return hoveredSeriesNames
    }
 
    @computed private get focusedEntityNames(): string[] {
        return this.selectedEntityNames
    }
 
    @computed private get selectedEntityNames(): string[] {
        return this.selectionArray.selectedEntityNames
    }
 
    @computed get displayStartTime(): string {
        return this.transformedTable.timeColumnFormatFunction(
            this.transformedTable.minTime ?? 1900
        )
    }
 
    @computed get displayEndTime(): string {
        return this.transformedTable.timeColumnFormatFunction(
            this.transformedTable.maxTime ?? 2000
        )
    }
 
    @computed private get arrowLegend(): ConnectedScatterLegend | undefined {
        if (
            this.displayStartTime === this.displayEndTime ||
            this.manager.isRelativeMode
        )
            return undefined
 
        return new ConnectedScatterLegend(this)
    }
 
    @action.bound private onScatterMouseOver(series: ScatterSeries): void {
        this.hoveredSeries = series.seriesName
    }
 
    @action.bound private onScatterMouseLeave(): void {
        this.hoveredSeries = undefined
    }
 
    @action.bound private onScatterClick(): void {
        if (this.hoveredSeries) this.onSelectEntity(this.hoveredSeries)
    }
 
    @computed private get tooltipSeries(): ScatterSeries | undefined {
        const { hoveredSeries, focusedEntityNames } = this
        if (hoveredSeries !== undefined)
            return this.series.find((g) => g.seriesName === hoveredSeries)
        if (focusedEntityNames && focusedEntityNames.length === 1)
            return this.series.find(
                (g) => g.seriesName === focusedEntityNames[0]
            )
        return undefined
    }
 
    @computed private get legendDimensions(): VerticalColorLegend {
        return new VerticalColorLegend({ manager: this })
    }
 
    @computed get maxLegendWidth(): number {
        return this.sidebarMaxWidth
    }
 
    @computed private get sidebarMinWidth(): number {
        return Math.max(this.bounds.width * 0.1, 60)
    }
 
    @computed private get sidebarMaxWidth(): number {
        return Math.max(this.bounds.width * 0.2, this.sidebarMinWidth)
    }
 
    @computed.struct get sidebarWidth(): number {
        const { legendDimensions, sidebarMinWidth, sidebarMaxWidth } = this
 
        return Math.max(
            Math.min(legendDimensions.width, sidebarMaxWidth),
            sidebarMinWidth
        )
    }
 
    // todo: Refactor
    @computed get dualAxis(): DualAxis {
        const { horizontalAxisPart, verticalAxisPart } = this
        return new DualAxis({
            bounds: this.bounds.padRight(this.sidebarWidth + 20),
            horizontalAxis: horizontalAxisPart,
            verticalAxis: verticalAxisPart,
        })
    }
 
    @computed get yAxis(): VerticalAxis {
        return this.dualAxis.verticalAxis
    }
 
    @computed get xAxis(): HorizontalAxis {
        return this.dualAxis.horizontalAxis
    }
 
    @computed private get comparisonLines():
        | ComparisonLineConfig[]
        | undefined {
        return this.manager.comparisonLines
    }
 
    @action.bound private onToggleEndpoints(): void {
        this.manager.compareEndPointsOnly =
            !this.compareEndPointsOnly || undefined
    }
 
    // Colors currently on the chart and not greyed out
    @computed get activeColors(): string[] {
        const { hoveredSeriesNames, focusedEntityNames } = this
        const activeKeys = hoveredSeriesNames.concat(focusedEntityNames)
 
        let series = this.series
 
        if (activeKeys.length)
            series = series.filter((g) => activeKeys.includes(g.seriesName))
 
        const colorValues = uniq(
            flatten(series.map((s) => s.points.map((p) => p.color)))
        )
        return excludeUndefined(
            colorValues.map((color) => this.colorScale.getColor(color))
        )
    }
 
    @computed private get hideConnectedScatterLines(): boolean {
        return !!this.manager.hideConnectedScatterLines
    }
 
    @computed private get points(): JSX.Element {
        const {
            dualAxis,
            focusedEntityNames,
            hoveredSeriesNames,
            hideConnectedScatterLines,
            manager,
            series,
            sizeDomain,
            colorScale,
            colorColumn,
        } = this
 
        return (
            <ScatterPointsWithLabels
                noDataModalManager={manager}
                hideConnectedScatterLines={hideConnectedScatterLines}
                seriesArray={series}
                dualAxis={dualAxis}
                colorScale={!colorColumn.isMissing ? colorScale : undefined}
                sizeDomain={sizeDomain}
                focusedSeriesNames={focusedEntityNames}
                hoveredSeriesNames={hoveredSeriesNames}
                onMouseOver={this.onScatterMouseOver}
                onMouseLeave={this.onScatterMouseLeave}
                onClick={this.onScatterClick}
            />
        )
    }
 
    @computed private get colorColumnSlug(): string | undefined {
        return this.manager.colorColumnSlug
    }
 
    @computed private get colorColumn(): CoreColumn {
        return this.transformedTable.get(this.colorColumnSlug)
    }
 
    @computed get legendItems(): ColorScaleBin[] {
        return this.colorScale.legendBins.filter((bin) =>
            this.colorsInUse.includes(bin.color)
        )
    }
 
    @computed get title(): string | undefined {
        return this.colorScale.legendDescription
    }
 
    componentDidMount(): void {
        exposeInstanceOnWindow(this)
    }
 
    render(): JSX.Element {
        if (this.failMessage)
            return (
                <NoDataModal
                    manager={this.manager}
                    bounds={this.bounds}
                    message={this.failMessage}
                />
            )
 
        const {
            bounds,
            dualAxis,
            arrowLegend,
            sidebarWidth,
            tooltipSeries,
            comparisonLines,
            legendDimensions,
        } = this
 
        return (
            <g className="ScatterPlot">
                <DualAxisComponent dualAxis={dualAxis} showTickMarks={false} />
                {comparisonLines &&
                    comparisonLines.map((line, i) => (
                        <ComparisonLine
                            key={i}
                            dualAxis={dualAxis}
                            comparisonLine={line}
                        />
                    ))}
                {this.points}
                <VerticalColorLegend manager={this} />
                {(arrowLegend || tooltipSeries) && (
                    <line
                        x1={bounds.right - sidebarWidth}
                        y1={bounds.top + legendDimensions.height + 2}
                        x2={bounds.right - 5}
                        y2={bounds.top + legendDimensions.height + 2}
                        stroke="#ccc"
                    />
                )}
                {arrowLegend && (
                    <g className="clickable" onClick={this.onToggleEndpoints}>
                        {arrowLegend.render(
                            bounds.right - sidebarWidth,
                            bounds.top + legendDimensions.height + 11
                        )}
                    </g>
                )}
                {tooltipSeries && (
                    <ScatterTooltip
                        yColumn={this.yColumn!}
                        xColumn={this.xColumn!}
                        series={tooltipSeries}
                        maxWidth={sidebarWidth}
                        fontSize={this.fontSize}
                        x={bounds.right - sidebarWidth}
                        y={
                            bounds.top +
                            legendDimensions.height +
                            11 +
                            (arrowLegend ? arrowLegend.height + 10 : 0)
                        }
                    />
                )}
            </g>
        )
    }
 
    @computed get legendY(): number {
        return this.bounds.top
    }
 
    @computed get legendX(): number {
        return this.bounds.right - this.sidebarWidth
    }
 
    colorScale = new ColorScale(this)
 
    @computed get colorScaleColumn(): CoreColumn {
        // We need to use inputTable in order to get consistent coloring for a variable across
        // charts, e.g. each continent being assigned to the same color.
        // inputTable is unfiltered, so it contains every value that exists in the variable.
        return this.inputTable.get(this.colorColumnSlug)
    }
 
    @computed get colorScaleConfig(): ColorScaleConfigDefaults | undefined {
        return (
            ColorScaleConfig.fromDSL(this.colorColumn.def) ??
            this.manager.colorScale
        )
    }
 
    defaultBaseColorScheme = ColorSchemeName.continents
    defaultNoDataColor = "#959595"
 
    @computed get hasNoDataBin(): boolean {
        if (this.colorColumn.isMissing) return false
        return this.colorColumn.valuesIncludingErrorValues.some(
            (value) => !isNotErrorValue(value)
        )
    }
 
    @computed private get yAxisConfig(): AxisConfig {
        return new AxisConfig(this.manager.yAxisConfig, this)
    }
 
    @computed private get xAxisConfig(): AxisConfig {
        return new AxisConfig(this.manager.xAxisConfig, this)
    }
 
    @computed private get yColumnSlug(): string {
        return autoDetectYColumnSlugs(this.manager)[0]
    }
 
    @computed private get yColumn(): CoreColumn {
        return this.transformedTable.get(this.yColumnSlug)
    }
 
    @computed private get xColumnSlug(): string {
        const { xColumnSlug } = this.manager
        return xColumnSlug ?? this.manager.table.timeColumn.slug
    }
 
    @computed private get xColumn(): CoreColumn {
        return this.transformedTable.get(this.xColumnSlug)
    }
 
    @computed private get sizeColumnSlug(): string | undefined {
        return this.manager.sizeColumnSlug
    }
 
    @computed private get sizeColumn(): CoreColumn {
        return this.transformedTable.get(this.sizeColumnSlug)
    }
 
    @computed get failMessage(): string {
        if (this.yColumn.isMissing) return "Missing Y axis variable"
 
        if (this.yColumn.isMissing) return "Missing X axis variable"
 
        if (isEmpty(this.allEntityNamesWithXAndY)) {
            if (
                this.manager.isRelativeMode &&
                this.manager.hasTimeline &&
                this.manager.startTime === this.manager.endTime
            ) {
                return "Please select a start and end point on the timeline below"
            }
            return "No entities with data for both X and Y"
        }
 
        if (isEmpty(this.series)) return "No matching data"
 
        return ""
    }
 
    // todo: remove this. Should be done as a simple column transform at the data level.
    // Possible to override the x axis dimension to target a special year
    // In case you want to graph say, education in the past and democracy today https://ourworldindata.org/grapher/correlation-between-education-and-democracy
    @computed get xOverrideTime(): number | undefined {
        return this.manager.xOverrideTime
    }
 
    // Unlike other charts, the scatterplot shows all available data by default, and the selection
    // is just for emphasis. But this behavior can be disabled.
    @computed private get hideBackgroundEntities(): boolean {
        return this.manager.addCountryMode === EntitySelectionMode.Disabled
    }
 
    @computed private get allEntityNamesWithXAndY(): EntityName[] {
        return intersection(
            this.yColumn.uniqEntityNames,
            this.xColumn.uniqEntityNames
        )
    }
 
    // todo: remove. do this at table filter level
    getSeriesNamesToShow(
        filterBackgroundEntities = this.hideBackgroundEntities
    ): Set<SeriesName> {
        const seriesNames = filterBackgroundEntities
            ? this.selectionArray.selectedEntityNames
            : this.allEntityNamesWithXAndY
 
        if (this.manager.matchingEntitiesOnly && !this.colorColumn.isMissing)
            return new Set(
                intersection(seriesNames, this.colorColumn.uniqEntityNames)
            )
 
        return new Set(seriesNames)
    }
 
    @computed get compareEndPointsOnly(): boolean {
        return !!this.manager.compareEndPointsOnly
    }
 
    @computed get allPoints(): SeriesPoint[] {
        return flatten(this.series.map((series) => series.points))
    }
 
    // domains across the entire timeline
    private domainDefault(property: "x" | "y"): [number, number] {
        const scaleType = property === "x" ? this.xScaleType : this.yScaleType
        if (!this.manager.useTimelineDomains) {
            return domainExtent(
                this.pointsForAxisDomains.map((point) => point[property]),
                scaleType,
                this.manager.zoomToSelection && this.selectedPoints.length
                    ? 1.1
                    : 1
            )
        }

        if (this.manager.isRelativeMode)
            return relativeMinAndMax(this.allPoints, property)

        return domainExtent(
            this.allPoints.map((v) => v[property]),
            scaleType
        )
    }
 
    @computed private get xDomainDefault(): [number, number] {
        return this.domainDefault("x")
    }
 
    @computed private get selectedPoints(): SeriesPoint[] {
        const seriesNamesSet = this.getSeriesNamesToShow(true)
        return this.allPoints.filter(
            (point) => point.entityName && seriesNamesSet.has(point.entityName)
        )
    }
 
    @computed private get pointsForAxisDomains(): SeriesPoint[] {
        if (
            !this.selectionArray.numSelectedEntities ||
            !this.manager.zoomToSelection
        )
            return this.allPoints

        return this.selectedPoints.length ? this.selectedPoints : this.allPoints
    }
 
    @computed private get sizeDomain(): [number, number] {
        if (this.sizeColumn.isMissing) return [1, 100]
        const sizeValues = this.transformedTable
            .get(this.sizeColumn.slug)
            .values.filter(isNumber)
        return domainExtent(sizeValues, ScaleType.linear)
    }
 
    @computed private get yScaleType(): ScaleType {
        return this.manager.isRelativeMode
            ? ScaleType.linear
            : this.yAxisConfig.scaleType || ScaleType.linear
    }
 
    @computed private get yDomainDefault(): [number, number] {
        return this.domainDefault("y")
    }
 
    @computed private get verticalAxisPart(): VerticalAxis {
        const { manager, yDomainDefault } = this
        const axisConfig = this.yAxisConfig
 
        const axis = axisConfig.toVerticalAxis()
        axis.formatColumn = this.yColumn
        const label = axisConfig.label || this.yColumn?.displayName || ""
        axis.scaleType = this.yScaleType
 
        if (manager.isRelativeMode) {
            axis.domain = yDomainDefault // Overwrite user's min/max
            if (label && label.length > 1) {
                axis.label = `Average annual change in ${lowerCaseFirstLetterUnlessAbbreviation(
                    label
                )}`
            }
        } else {
            axis.updateDomainPreservingUserSettings(yDomainDefault)
            axis.label = label
        }
 
        return axis
    }
 
    @computed private get xScaleType(): ScaleType {
        return this.manager.isRelativeMode
            ? ScaleType.linear
            : this.xAxisConfig.scaleType ?? ScaleType.linear
    }
 
    @computed private get xAxisLabelBase(): string {
        const xDimName = this.xColumn?.displayName
        if (this.xOverrideTime !== undefined)
            return `${xDimName} in ${this.xOverrideTime}`
        return xDimName
    }
 
    @computed private get horizontalAxisPart(): HorizontalAxis {
        const { xDomainDefault, manager, xAxisLabelBase } = this
        const { xAxisConfig } = this
        const axis = xAxisConfig.toHorizontalAxis()
        axis.formatColumn = this.xColumn
        axis.scaleType = this.xScaleType
        if (manager.isRelativeMode) {
            axis.domain = xDomainDefault // Overwrite user's min/max
            const label = xAxisConfig.label || xAxisLabelBase
            if (label && label.length > 1) {
                axis.label = `Average annual change in ${lowerCaseFirstLetterUnlessAbbreviation(
                    label
                )}`
            }
        } else {
            axis.updateDomainPreservingUserSettings(xDomainDefault)
            const label = xAxisConfig.label || xAxisLabelBase
            if (label) axis.label = label
        }
        return axis
    }
 
    getPointLabel(row: OwidRow): string | undefined {
        const strat = this.manager.scatterPointLabelStrategy
        let label
        if (strat === ScatterPointLabelStrategy.y) {
            label = this.yColumn?.formatValue(row[this.yColumnSlug])
        } else if (strat === ScatterPointLabelStrategy.x) {
            label = this.xColumn?.formatValue(row[this.xColumnSlug])
        } else {
            label = this.transformedTable.timeColumnFormatFunction(
                row[this.transformedTable.timeColumn.slug]
            )
        }
        return label
    }
 
    private removePointsOutsidePlane(points: SeriesPoint[]): SeriesPoint[] {
        const { yAxisConfig, xAxisConfig } = this
        if (
            yAxisConfig.removePointsOutsideDomain ||
            xAxisConfig.removePointsOutsideDomain
        ) {
            return points.filter((point) => {
                return (
                    !xAxisConfig.shouldRemovePoint(point.x) &&
                    !yAxisConfig.shouldRemovePoint(point.y)
                )
            })
        }
        return points
    }
 
    @computed private get allPointsBeforeEndpointsFilter(): SeriesPoint[] {
        const { entityNameSlug, timeColumn } = this.transformedTable
        // We are running this filter first because it only depends on author-specified config, not
        // on any user interaction.
        return this.removePointsOutsidePlane(
            this.transformedTable.rows.map((row) => {
                return {
                    x: row[this.xColumnSlug],
                    y: row[this.yColumnSlug],
                    size: defaultIfErrorValue(row[this.sizeColumn.slug], 0),
                    color: defaultIfErrorValue(
                        row[this.colorColumn.slug],
                        undefined
                    ),
                    entityName: row[entityNameSlug],
                    label: this.getPointLabel(row) ?? "",
                    timeValue: row[timeColumn.slug],
                    time: {
                        x: row[this.xColumn!.originalTimeColumnSlug!],
                        y: row[this.yColumn!.originalTimeColumnSlug!],
                    },
                }
            })
        )
    }
 
    @computed get series(): ScatterSeries[] {
        return Object.entries(
            groupBy(this.allPointsBeforeEndpointsFilter, (p) => p.entityName)
        ).map(([entityName, points]) => {
            const series: ScatterSeries = {
                seriesName: entityName,
                label: entityName,
                color: "#932834", // Default color, used when no color dimension is present
                size: this.getSizeFromPoints(points),
                points,
            }
            this.assignColorToSeries(entityName, series)
            return series
        })
    }
 
    private assignColorToSeries(
        entityName: EntityName,
        series: ScatterSeries
    ): void {
        if (series.points.length) {
            const keyColor =
                this.transformedTable.getColorForEntityName(entityName)
            if (keyColor !== undefined) series.color = keyColor
            else if (!this.colorColumn.isMissing) {
                const colorValue = last(
                    series.points.map((point) => point.color)
                )
                const color = this.colorScale.getColor(colorValue)
                if (color !== undefined) {
                    series.color = color
                    series.isScaleColor = true
                }
            }
        }
    }
 
    private getSizeFromPoints(points: SeriesPoint[]): number {
        const size = last(points.map((v) => v.size).filter(isNumber))
        return size ?? 0
    }
}