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 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 | 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 3x 3x 1x 1x 3x 3x 3x 4x 4x 4x 4x 4x 4x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 3x 3x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 3x 3x 1x 1x 1x 1x 3x 3x 1x 1x 3x 3x 3x 1x 1x 1x 3x 3x 3x 2x 2x 3x 1x 1x 1x 1x 1x 3x 3x 3x 3x 1x 1x 4x 4x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 2x 2x 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 1x 4x 3x 3x 3x 1x 1x 1x 1x 3x 3x 1x 1x 3x 3x 1x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 4x 4x 4x 4x 4x 1x 1x 4x 4x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 10x 10x 10x 10x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 30x 30x 30x 30x 30x 30x 1420x 60x 60x 60x 60x 60x 60x 30x 30x 30x 20x 20x 30x 30x 30x 30x 30x 30x 30x 30x 3x 3x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 9x 9x 9x 9x 9x 9x 9x 1x 1x 6x 6x 1x 1x 6x 6x 6x 6x 6x 6x 6x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 6x 6x 6x 1x 1x 1x 30x 30x 30x 30x 30x 30x 30x 10x 10x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 25x 25x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 23x 23x 23x 23x 30x 30x 30x 30x 30x 30x 30x 23x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 30x 30x 30x 30x 30x 30x 3x 3x 3x 15x 15x 15x 15x 15x 15x 15x 10x 10x 10x 10x 9x 8x 8x 8x 8x 15x 15x 3x 3x 3x 30x 300x 300x | import * as React from "react" import { intersection, without, uniq, isEmpty, last, sortBy, max, flatten, getRelativeMouse, domainExtent, minBy, maxBy, exposeInstanceOnWindow, } from "../../clientUtils/Util" import { observable, computed, action } from "mobx" import { observer } from "mobx-react" import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds" import { NoDataModal } from "../noDataModal/NoDataModal" import { VerticalColorLegend, VerticalColorLegendManager, } from "../verticalColorLegend/VerticalColorLegend" import { ColorScale, ColorScaleManager } from "../color/ColorScale" import { BASE_FONT_SIZE, ScaleType, EntitySelectionMode, SeriesName, } from "../core/GrapherConstants" import { ChartInterface } from "../chart/ChartInterface" import { ChartManager } from "../chart/ChartManager" import { scaleLinear, scaleLog, ScaleLinear, ScaleLogarithmic } from "d3-scale" import { extent } from "d3-array" import { select } from "d3-selection" import { Text } from "../text/Text" import { TextWrap } from "../text/TextWrap" import { DEFAULT_SLOPE_CHART_COLOR, LabelledSlopesProps, SlopeAxisProps, SlopeChartSeries, SlopeChartValue, SlopeProps, } from "./SlopeChartConstants" import { CoreColumn } from "../../coreTable/CoreTableColumns" import { OwidTable } from "../../coreTable/OwidTable" import { Color } from "../../coreTable/CoreTableConstants" import { autoDetectYColumnSlugs, makeSelectionArray } from "../chart/ChartUtils" import { ColorSchemeName } from "../color/ColorConstants" import { AxisConfig, FontSizeManager } from "../axis/AxisConfig" @observer export class SlopeChart extends React.Component<{ bounds?: Bounds manager: ChartManager }> implements ChartInterface, VerticalColorLegendManager, ColorScaleManager { // currently hovered individual series key @observable hoverKey?: string // currently hovered legend color @observable hoverColor?: string transformTable(table: OwidTable) { if (!table.has(this.yColumnSlug)) return table // TODO: remove this filter once we don't have mixed type columns in datasets table = table.replaceNonNumericCellsWithErrorValues([this.yColumnSlug]) return table .dropRowsWithErrorValuesForColumn(this.yColumnSlug) .interpolateColumnWithTolerance(this.yColumnSlug) } @computed get manager() { return this.props.manager } @computed.struct get bounds() { return this.props.bounds ?? DEFAULT_BOUNDS } @computed get fontSize() { return this.manager.baseFontSize ?? BASE_FONT_SIZE } @computed get legendItems() { return this.colorScale.legendBins .filter((bin) => this.colorsInUse.includes(bin.color)) .map((bin) => { return { key: bin.label ?? "", label: bin.label ?? "", color: bin.color, } }) } @computed get maxLegendWidth() { return this.sidebarMaxWidth } @action.bound onSlopeMouseOver(slopeProps: SlopeProps) { this.hoverKey = slopeProps.seriesName } @action.bound onSlopeMouseLeave() { this.hoverKey = undefined } @action.bound onSlopeClick() { const { manager, hoverKey } = this if ( manager.addCountryMode === EntitySelectionMode.Disabled || !manager.addCountryMode || hoverKey === undefined ) { return } this.selectionArray.toggleSelection(hoverKey) } @action.bound onLegendMouseOver(color: string) { this.hoverColor = color } @action.bound onLegendMouseLeave() { this.hoverColor = undefined } @computed private get selectionArray() { return makeSelectionArray(this.manager) } @computed private get selectedEntityNames() { return this.selectionArray.selectedEntityNames } // When the color legend is clicked, toggle selection fo all associated keys @action.bound onLegendClick() { const { manager, hoverColor } = this if ( manager.addCountryMode === EntitySelectionMode.Disabled || !manager.addCountryMode || hoverColor === undefined ) return const seriesNamesToToggle = this.series .filter((g) => g.color === hoverColor) .map((g) => g.seriesName) const areAllSeriesActive = intersection(seriesNamesToToggle, this.selectedEntityNames) .length === seriesNamesToToggle.length if (areAllSeriesActive) this.selectionArray.setSelectedEntities( without(this.selectedEntityNames, ...seriesNamesToToggle) ) else this.selectionArray.setSelectedEntities( this.selectedEntityNames.concat(seriesNamesToToggle) ) } // Colors on the legend for which every matching group is focused @computed get focusColors() { const { colorsInUse } = this return colorsInUse.filter((color) => { const matchingSeriesNames = this.series .filter((g) => g.color === color) .map((g) => g.seriesName) return ( intersection(matchingSeriesNames, this.selectedEntityNames) .length === matchingSeriesNames.length ) }) } @computed get focusKeys() { return this.selectedEntityNames } // All currently hovered group keys, combining the legend and the main UI @computed.struct get hoverKeys() { const { hoverColor, hoverKey } = this const hoverKeys = hoverColor === undefined ? [] : uniq( this.series .filter((g) => g.color === hoverColor) .map((g) => g.seriesName) ) if (hoverKey !== undefined) hoverKeys.push(hoverKey) return hoverKeys } // Colors currently on the chart and not greyed out @computed get activeColors() { const { hoverKeys, focusKeys } = this const activeKeys = hoverKeys.concat(focusKeys) if (activeKeys.length === 0) // No hover or focus means they're all active by default return uniq(this.series.map((g) => g.color)) return uniq( this.series .filter((g) => activeKeys.indexOf(g.seriesName) !== -1) .map((g) => g.color) ) } // Only show colors on legend that are actually in use @computed private get colorsInUse() { return uniq(this.series.map((series) => series.color)) } @computed private get sidebarMaxWidth() { return this.bounds.width * 0.5 } private sidebarMinWidth = 100 @computed private get legendWidth() { return new VerticalColorLegend({ manager: this }).width } @computed.struct private get sidebarWidth() { const { sidebarMinWidth, sidebarMaxWidth, legendWidth } = this return Math.max(Math.min(legendWidth, sidebarMaxWidth), sidebarMinWidth) } // correction is to account for the space taken by the legend @computed private get innerBounds() { const { sidebarWidth, showLegend } = this return showLegend ? this.bounds.padRight(sidebarWidth + 20) : this.bounds } // verify the validity of data used to show legend // this is for backwards compatibility with charts that were added without legend // eg: https://ourworldindata.org/grapher/mortality-rate-improvement-by-cohort @computed private get showLegend() { const { colorsInUse } = this const { legendBins } = this.colorScale return legendBins.some((bin) => colorsInUse.includes(bin.color)) } render() { if (this.failMessage) return ( <NoDataModal manager={this.manager} bounds={this.props.bounds} message={this.failMessage} /> ) const { manager } = this.props const { series, focusKeys, hoverKeys, innerBounds, showLegend } = this const legend = showLegend ? ( <VerticalColorLegend manager={this} /> ) : ( <div></div> ) return ( <g className="slopeChart"> <LabelledSlopes manager={manager} bounds={innerBounds} yColumn={this.yColumn!} seriesArr={series} focusKeys={focusKeys} hoverKeys={hoverKeys} onMouseOver={this.onSlopeMouseOver} onMouseLeave={this.onSlopeMouseLeave} onClick={this.onSlopeClick} /> {legend} </g> ) } @computed get legendY() { return this.bounds.top } @computed get legendX(): number { return this.bounds.right - this.sidebarWidth } @computed get failMessage() { if (this.yColumn.isMissing) return "Missing Y column" else if (isEmpty(this.series)) return "No matching data" return "" } colorScale = new ColorScale(this) @computed get colorScaleConfig() { return this.manager.colorScale } @computed get colorScaleColumn() { return this.colorColumn } defaultBaseColorScheme = ColorSchemeName.continents @computed private get yColumn() { return this.transformedTable.get(this.yColumnSlug) } @computed protected get yColumnSlug() { return autoDetectYColumnSlugs(this.manager)[0] } @computed private get colorColumn() { // NB: This is tricky. Often it seems we use the Continent variable (123) for colors, but we only have 1 year for that variable, which // would likely get filtered by any time filtering. So we need to jump up to the root table to get the color values we want. // We should probably refactor this as part of a bigger color refactoring. return this.inputTable.get(this.manager.colorColumnSlug) } @computed get transformedTable() { return ( this.manager.transformedTable ?? this.transformTable(this.inputTable) ) } @computed get inputTable() { return this.manager.table } // helper method to directly get the associated color value given an Entity // dimension data saves color a level deeper. eg: { Afghanistan => { 2015: Asia|Color }} // this returns that data in the form { Afghanistan => Asia } @computed private get colorBySeriesName(): Map< SeriesName, Color | undefined > { const { colorScale, colorColumn } = this if (colorColumn.isMissing) return new Map() const colorByEntity = new Map<SeriesName, Color | undefined>() colorColumn.valueByEntityNameAndOriginalTime.forEach( (timeToColorMap, seriesName) => { const values = Array.from(timeToColorMap.values()) const key = last(values) colorByEntity.set(seriesName, colorScale.getColor(key)) } ) return colorByEntity } @computed private get sizeColumn() { return this.transformedTable.get(this.manager.sizeColumnSlug) } // helper method to directly get the associated size value given an Entity // dimension data saves size a level deeper. eg: { Afghanistan => { 1990: 1, 2015: 10 }} // this returns that data in the form { Afghanistan => 1 } @computed private get sizeByEntity(): Map<string, any> { const sizeCol = this.sizeColumn const sizeByEntity = new Map<string, any>() if (sizeCol) sizeCol.valueByEntityNameAndOriginalTime.forEach( (timeToSizeMap, entity) => { const values = Array.from(timeToSizeMap.values()) sizeByEntity.set(entity, values[0]) // hack: default to the value associated with the first time } ) return sizeByEntity } componentDidMount() { exposeInstanceOnWindow(this) } @computed get series() { const column = this.yColumn if (!column) return [] const { colorBySeriesName, sizeByEntity } = this const { minTime, maxTime } = column const table = this.inputTable return column.uniqEntityNames .map((seriesName) => { const values: SlopeChartValue[] = [] const yValues = column.valueByEntityNameAndOriginalTime.get(seriesName)! || [] yValues.forEach((value, time) => { if (time !== minTime && time !== maxTime) return values.push({ x: time, y: value, }) }) const color = table.getColorForEntityName(seriesName) ?? colorBySeriesName.get(seriesName) ?? DEFAULT_SLOPE_CHART_COLOR return { seriesName, color, size: sizeByEntity.get(seriesName) || 1, values, } as SlopeChartSeries }) .filter((series) => series.values.length >= 2) } } @observer class SlopeChartAxis extends React.Component<SlopeAxisProps> { static calculateBounds( containerBounds: Bounds, props: { column: CoreColumn orient: "left" | "right" scale: ScaleLinear<number, number> } ) { const { scale, column } = props const longestTick = maxBy( scale.ticks(6).map((tick) => column.formatValueShort(tick)), (tick) => tick.length ) const axisWidth = Bounds.forText(longestTick).width return new Bounds( containerBounds.x, containerBounds.y, axisWidth, containerBounds.height ) } static getTicks( scale: ScaleLinear<number, number> | ScaleLogarithmic<number, number>, scaleType: ScaleType ) { if (scaleType === ScaleType.log) { let minPower10 = Math.ceil( Math.log(scale.domain()[0]) / Math.log(10) ) if (!isFinite(minPower10)) minPower10 = 0 let maxPower10 = Math.floor( Math.log(scale.domain()[1]) / Math.log(10) ) if (maxPower10 <= minPower10) maxPower10 += 1 const tickValues = [] for (let i = minPower10; i <= maxPower10; i++) { tickValues.push(Math.pow(10, i)) } return tickValues } else { return scale.ticks(6) } } @computed get ticks() { return SlopeChartAxis.getTicks(this.props.scale, this.props.scaleType) } render() { const { bounds, scale, orient, column } = this.props const { ticks } = this const textColor = "#666" return ( <g className="axis" fontSize="0.8em"> {ticks.map((tick, i) => { return ( <text key={i} x={orient === "left" ? bounds.left : bounds.right} y={scale(tick)} fill={textColor} dominantBaseline="middle" textAnchor={orient === "left" ? "start" : "end"} > {column.formatValueShort(tick)} </text> ) })} </g> ) } } @observer class Slope extends React.Component<SlopeProps> { line: SVGElement | null = null @computed get isInBackground() { const { isLayerMode, isHovered, isFocused } = this.props if (!isLayerMode) return false return !(isHovered || isFocused) } render() { const { x1, y1, x2, y2, color, size, hasLeftLabel, hasRightLabel, leftValueStr, rightValueStr, leftLabel, rightLabel, labelFontSize, leftLabelBounds, rightLabelBounds, isFocused, isHovered, } = this.props const { isInBackground } = this const lineColor = isInBackground ? "#e2e2e2" : color //'#89C9CF' const labelColor = isInBackground ? "#aaa" : "#333" const opacity = isHovered ? 1 : isFocused ? 0.7 : 0.5 const lineStrokeWidth = isHovered ? size * 2 : isFocused ? 1.5 * size : size const leftValueLabelBounds = Bounds.forText(leftValueStr, { fontSize: labelFontSize, }) const rightValueLabelBounds = Bounds.forText(rightValueStr, { fontSize: labelFontSize, }) return ( <g className="slope"> {hasLeftLabel && leftLabel.render( leftLabelBounds.x + leftLabelBounds.width, leftLabelBounds.y, { textAnchor: "end", fill: labelColor, fontWeight: isFocused || isHovered ? "bold" : undefined, } )} {hasLeftLabel && ( <Text x={x1 - 8} y={y1 - leftValueLabelBounds.height / 2} textAnchor="end" fontSize={labelFontSize} fill={labelColor} fontWeight={isFocused || isHovered ? "bold" : undefined} > {leftValueStr} </Text> )} <circle cx={x1} cy={y1} r={isFocused || isHovered ? 4 : 2} fill={lineColor} opacity={opacity} /> <line ref={(el) => (this.line = el)} x1={x1} y1={y1} x2={x2} y2={y2} stroke={lineColor} strokeWidth={lineStrokeWidth} opacity={opacity} /> <circle cx={x2} cy={y2} r={isFocused || isHovered ? 4 : 2} fill={lineColor} opacity={opacity} /> {hasRightLabel && ( <Text x={x2 + 8} y={y2 - rightValueLabelBounds.height / 2} fontSize={labelFontSize} fill={labelColor} fontWeight={isFocused || isHovered ? "bold" : undefined} > {rightValueStr} </Text> )} {hasRightLabel && rightLabel.render(rightLabelBounds.x, rightLabelBounds.y, { fill: labelColor, fontWeight: isFocused || isHovered ? "bold" : undefined, })} </g> ) } } @observer class LabelledSlopes extends React.Component<LabelledSlopesProps> implements FontSizeManager { base: React.RefObject<SVGGElement> = React.createRef() @computed private get data() { return this.props.seriesArr } @computed private get yColumn() { return this.props.yColumn } @computed private get manager() { return this.props.manager } @computed private get bounds() { return this.props.bounds } @computed get fontSize() { return this.manager.baseFontSize ?? BASE_FONT_SIZE } @computed private get focusedSeriesNames() { return intersection( this.props.focusKeys || [], this.data.map((g) => g.seriesName) ) } @computed private get hoveredSeriesNames() { return intersection( this.props.hoverKeys || [], this.data.map((g) => g.seriesName) ) } // Layered mode occurs when any entity on the chart is hovered or focused // Then, a special "foreground" set of entities is rendered over the background @computed private get isLayerMode() { return ( this.focusedSeriesNames.length > 0 || this.hoveredSeriesNames.length > 0 ) } @computed private get isPortrait() { return this.bounds.width < 400 } @computed private get allValues() { return flatten(this.props.seriesArr.map((g) => g.values)) } @computed private get xDomainDefault(): [number, number] { return domainExtent( this.allValues.map((v) => v.x), ScaleType.linear ) } @computed private get yAxisConfig(): AxisConfig { return new AxisConfig(this.manager.yAxisConfig, this) } @computed private get yScaleType() { return this.yAxisConfig.scaleType || ScaleType.linear } @computed private get yDomainDefault(): [number, number] { return domainExtent( this.allValues.map((v) => v.y), this.yScaleType || ScaleType.linear ) } @computed private get xDomain(): [number, number] { return this.xDomainDefault } @computed private get yDomain(): [number, number] { const domain = this.yAxisConfig.domain || [Infinity, -Infinity] const domainDefault = this.yDomainDefault return [ Math.min(domain[0], domainDefault[0]), Math.max(domain[1], domainDefault[1]), ] } @computed get sizeScale(): ScaleLinear<number, number> { return scaleLinear() .domain( extent(this.props.seriesArr.map((series) => series.size)) as [ number, number ] ) .range([1, 4]) } @computed get yScaleConstructor(): any { return this.yScaleType === ScaleType.log ? scaleLog : scaleLinear } @computed private get yScale(): | ScaleLinear<number, number> | ScaleLogarithmic<number, number> { return this.yScaleConstructor() .domain(this.yDomain) .range(this.props.bounds.padBottom(50).yRange()) } @computed private get xScale(): ScaleLinear<number, number> { const { bounds, isPortrait, xDomain, yScale, yColumn } = this const padding = isPortrait ? 0 : SlopeChartAxis.calculateBounds(bounds, { orient: "left", scale: yScale, column: yColumn, }).width return scaleLinear() .domain(xDomain) .range(bounds.padWidth(padding).xRange()) } @computed get maxLabelWidth() { return this.bounds.width / 5 } @computed private get initialSlopeData() { const { data, isPortrait, xScale, yScale, sizeScale, yColumn, maxLabelWidth: maxWidth, } = this const slopeData: SlopeProps[] = [] const yDomain = yScale.domain() data.forEach((series) => { // Ensure values fit inside the chart if ( !series.values.every( (d) => d.y >= yDomain[0] && d.y <= yDomain[1] ) ) return const text = series.seriesName const [v1, v2] = series.values const [x1, x2] = [xScale(v1.x), xScale(v2.x)] const [y1, y2] = [yScale(v1.y), yScale(v2.y)] const fontSize = (isPortrait ? 0.6 : 0.65) * this.fontSize const leftValueStr = yColumn.formatValueShort(v1.y) const rightValueStr = yColumn.formatValueShort(v2.y) const leftValueWidth = Bounds.forText(leftValueStr, { fontSize, }).width const rightValueWidth = Bounds.forText(rightValueStr, { fontSize, }).width const leftLabel = new TextWrap({ maxWidth, fontSize, text, }) const rightLabel = new TextWrap({ maxWidth, fontSize, text, }) slopeData.push({ x1, y1, x2, y2, color: series.color, size: sizeScale(series.size) || 1, leftValueStr, rightValueStr, leftValueWidth, rightValueWidth, leftLabel, rightLabel, labelFontSize: fontSize, seriesName: series.seriesName, isFocused: false, isHovered: false, hasLeftLabel: true, hasRightLabel: true, } as SlopeProps) }) return slopeData } @computed get maxValueWidth() { return max(this.initialSlopeData.map((s) => s.leftValueWidth)) as number } @computed private get labelAccountedSlopeData() { const { maxLabelWidth, maxValueWidth } = this return this.initialSlopeData.map((slope) => { // Squish slopes to make room for labels const x1 = slope.x1 + maxLabelWidth + maxValueWidth + 8 const x2 = slope.x2 - maxLabelWidth - maxValueWidth - 8 // Position the labels const leftLabelBounds = new Bounds( x1 - slope.leftValueWidth - 12 - slope.leftLabel.width, slope.y1 - slope.leftLabel.height / 2, slope.leftLabel.width, slope.leftLabel.height ) const rightLabelBounds = new Bounds( x2 + slope.rightValueWidth + 12, slope.y2 - slope.rightLabel.height / 2, slope.rightLabel.width, slope.rightLabel.height ) return { ...slope, x1: x1, x2: x2, leftLabelBounds: leftLabelBounds, rightLabelBounds: rightLabelBounds, } }) } @computed get backgroundGroups() { return this.slopeData.filter( (group) => !(group.isHovered || group.isFocused) ) } @computed get foregroundGroups() { return this.slopeData.filter( (group) => !!(group.isHovered || group.isFocused) ) } // Get the final slope data with hover focusing and collision detection @computed get slopeData(): SlopeProps[] { const { focusedSeriesNames, hoveredSeriesNames } = this let slopeData = this.labelAccountedSlopeData slopeData = slopeData.map((slope) => { return { ...slope, isFocused: focusedSeriesNames.includes(slope.seriesName), isHovered: hoveredSeriesNames.includes(slope.seriesName), } }) // How to work out which of two slopes to prioritize for labelling conflicts function chooseLabel(s1: SlopeProps, s2: SlopeProps) { if (s1.isHovered && !s2.isHovered) // Hovered slopes always have priority return s1 else if (!s1.isHovered && s2.isHovered) return s2 else if (s1.isFocused && !s2.isFocused) // Focused slopes are next in priority return s1 else if (!s1.isFocused && s2.isFocused) return s2 else if (s1.hasLeftLabel && !s2.hasLeftLabel) // Slopes which already have one label are prioritized for the other side return s1 else if (!s1.hasLeftLabel && s2.hasLeftLabel) return s2 else if (s1.size > s2.size) // Larger sizes get the next priority return s1 else if (s2.size > s1.size) return s2 else return s1 // Equal priority, just do the first one } // Eliminate overlapping labels, one pass for each side slopeData.forEach((s1) => { slopeData.forEach((s2) => { if ( s1 !== s2 && s1.hasLeftLabel && s2.hasLeftLabel && s1.leftLabelBounds.intersects(s2.leftLabelBounds) ) { if (chooseLabel(s1, s2) === s1) s2.hasLeftLabel = false else s1.hasLeftLabel = false } }) }) slopeData.forEach((s1) => { slopeData.forEach((s2) => { if ( s1 !== s2 && s1.hasRightLabel && s2.hasRightLabel && s1.rightLabelBounds.intersects(s2.rightLabelBounds) ) { if (chooseLabel(s1, s2) === s1) s2.hasRightLabel = false else s1.hasRightLabel = false } }) }) // Order by focus/hover and size for draw order slopeData = sortBy(slopeData, (slope) => slope.size) slopeData = sortBy(slopeData, (slope) => slope.isFocused || slope.isHovered ? 1 : 0 ) return slopeData } mouseFrame?: number @action.bound onMouseLeave() { if (this.mouseFrame !== undefined) cancelAnimationFrame(this.mouseFrame) if (this.props.onMouseLeave) this.props.onMouseLeave() } @action.bound onMouseMove( ev: React.MouseEvent<SVGGElement> | React.TouchEvent<SVGGElement> ) { if (this.base.current) { const mouse = getRelativeMouse(this.base.current, ev.nativeEvent) this.mouseFrame = requestAnimationFrame(() => { if (this.props.bounds.contains(mouse)) { const distToSlope = new Map<SlopeProps, number>() for (const s of this.slopeData) { const dist = Math.abs( (s.y2 - s.y1) * mouse.x - (s.x2 - s.x1) * mouse.y + s.x2 * s.y1 - s.y2 * s.x1 ) / Math.sqrt((s.y2 - s.y1) ** 2 + (s.x2 - s.x1) ** 2) distToSlope.set(s, dist) } const closestSlope = minBy(this.slopeData, (s) => distToSlope.get(s) ) if ( closestSlope && (distToSlope.get(closestSlope) as number) < 20 && this.props.onMouseOver ) { this.props.onMouseOver(closestSlope) } else { this.props.onMouseLeave() } } }) } } @action.bound onClick() { if (this.props.onClick) this.props.onClick() } componentDidMount() { this.playIntroAnimation() } private playIntroAnimation() { // Nice little intro animation select(this.base.current) .select(".slopes") .attr("stroke-dasharray", "100%") .attr("stroke-dashoffset", "100%") .transition() .attr("stroke-dashoffset", "0%") } renderGroups(groups: SlopeProps[]) { const { isLayerMode } = this return groups.map((slope) => ( <Slope key={slope.seriesName} {...slope} isLayerMode={isLayerMode} /> )) } render() { const { fontSize, yScaleType, bounds, slopeData, isPortrait, xDomain, yScale, onMouseMove, yColumn, } = this if (isEmpty(slopeData)) return <NoDataModal manager={this.props.manager} bounds={bounds} /> const { x1, x2 } = slopeData[0] const [y1, y2] = yScale.range() return ( <g className="LabelledSlopes" ref={this.base} onMouseMove={onMouseMove} onTouchMove={onMouseMove} onTouchStart={onMouseMove} onMouseLeave={this.onMouseLeave} onClick={this.onClick} > <rect x={bounds.x} y={bounds.y} width={bounds.width} height={bounds.height} fill="rgba(255,255,255,0)" opacity={0} /> <g className="gridlines"> {SlopeChartAxis.getTicks(yScale, yScaleType).map( (tick, i) => { return ( <line key={i} x1={x1} y1={yScale(tick)} x2={x2} y2={yScale(tick)} stroke="#eee" strokeDasharray="3,2" /> ) } )} </g> {!isPortrait && ( <SlopeChartAxis orient="left" column={yColumn} scale={yScale} scaleType={yScaleType} bounds={bounds} /> )} {!isPortrait && ( <SlopeChartAxis orient="right" column={yColumn} scale={yScale} scaleType={yScaleType} bounds={bounds} /> )} <line x1={x1} y1={y1} x2={x1} y2={y2} stroke="#333" /> <line x1={x2} y1={y1} x2={x2} y2={y2} stroke="#333" /> <Text x={x1} y={y1 + 10} textAnchor="middle" fill="#666" fontSize={fontSize} > {xDomain[0].toString()} </Text> <Text x={x2} y={y1 + 10} textAnchor="middle" fill="#666" fontSize={fontSize} > {xDomain[1].toString()} </Text> <g className="slopes"> {this.renderGroups(this.backgroundGroups)} {this.renderGroups(this.foregroundGroups)} </g> </g> ) } } |