File: test_plotting.py

package info (click to toggle)
python-geopandas 0.8.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 12,004 kB
  • sloc: python: 14,226; makefile: 150; sh: 14
file content (1404 lines) | stat: -rw-r--r-- 55,179 bytes parent folder | download
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
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
import itertools
import warnings

import numpy as np
import pandas as pd

from shapely.affinity import rotate
from shapely.geometry import (
    MultiPolygon,
    Polygon,
    LineString,
    LinearRing,
    Point,
    MultiPoint,
    MultiLineString,
    GeometryCollection,
)


from geopandas import GeoDataFrame, GeoSeries, read_file
from geopandas.datasets import get_path

import pytest

matplotlib = pytest.importorskip("matplotlib")
matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa


@pytest.fixture(autouse=True)
def close_figures(request):
    yield
    plt.close("all")


try:
    cycle = matplotlib.rcParams["axes.prop_cycle"].by_key()
    MPL_DFT_COLOR = cycle["color"][0]
except KeyError:
    MPL_DFT_COLOR = matplotlib.rcParams["axes.color_cycle"][0]


class TestPointPlotting:
    def setup_method(self):
        self.N = 10
        self.points = GeoSeries(Point(i, i) for i in range(self.N))

        values = np.arange(self.N)

        self.df = GeoDataFrame({"geometry": self.points, "values": values})
        self.df["exp"] = (values * 10) ** 3

        multipoint1 = MultiPoint(self.points)
        multipoint2 = rotate(multipoint1, 90)
        self.df2 = GeoDataFrame(
            {"geometry": [multipoint1, multipoint2], "values": [0, 1]}
        )

    def test_figsize(self):

        ax = self.points.plot(figsize=(1, 1))
        np.testing.assert_array_equal(ax.figure.get_size_inches(), (1, 1))

        ax = self.df.plot(figsize=(1, 1))
        np.testing.assert_array_equal(ax.figure.get_size_inches(), (1, 1))

    def test_default_colors(self):

        # # without specifying values -> uniform color

        # GeoSeries
        ax = self.points.plot()
        _check_colors(
            self.N, ax.collections[0].get_facecolors(), [MPL_DFT_COLOR] * self.N
        )

        # GeoDataFrame
        ax = self.df.plot()
        _check_colors(
            self.N, ax.collections[0].get_facecolors(), [MPL_DFT_COLOR] * self.N
        )

        # # with specifying values -> different colors for all 10 values
        ax = self.df.plot(column="values")
        cmap = plt.get_cmap()
        expected_colors = cmap(np.arange(self.N) / (self.N - 1))
        _check_colors(self.N, ax.collections[0].get_facecolors(), expected_colors)

    def test_colormap(self):

        # without specifying values but cmap specified -> no uniform color
        # but different colors for all points

        # GeoSeries
        ax = self.points.plot(cmap="RdYlGn")
        cmap = plt.get_cmap("RdYlGn")
        exp_colors = cmap(np.arange(self.N) / (self.N - 1))
        _check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)

        ax = self.df.plot(cmap="RdYlGn")
        _check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)

        # # with specifying values -> different colors for all 10 values
        ax = self.df.plot(column="values", cmap="RdYlGn")
        cmap = plt.get_cmap("RdYlGn")
        _check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)

        # when using a cmap with specified lut -> limited number of different
        # colors
        ax = self.points.plot(cmap=plt.get_cmap("Set1", lut=5))
        cmap = plt.get_cmap("Set1", lut=5)
        exp_colors = cmap(list(range(5)) * 3)
        _check_colors(self.N, ax.collections[0].get_facecolors(), exp_colors)

    def test_single_color(self):

        ax = self.points.plot(color="green")
        _check_colors(self.N, ax.collections[0].get_facecolors(), ["green"] * self.N)

        ax = self.df.plot(color="green")
        _check_colors(self.N, ax.collections[0].get_facecolors(), ["green"] * self.N)

        # check rgba tuple GH1178
        ax = self.df.plot(color=(0.5, 0.5, 0.5))
        _check_colors(
            self.N, ax.collections[0].get_facecolors(), [(0.5, 0.5, 0.5)] * self.N
        )
        ax = self.df.plot(color=(0.5, 0.5, 0.5, 0.5))
        _check_colors(
            self.N, ax.collections[0].get_facecolors(), [(0.5, 0.5, 0.5, 0.5)] * self.N
        )
        with pytest.raises((ValueError, TypeError)):
            self.df.plot(color="not color")

        with warnings.catch_warnings(record=True) as _:  # don't print warning
            # 'color' overrides 'column'
            ax = self.df.plot(column="values", color="green")
            _check_colors(
                self.N, ax.collections[0].get_facecolors(), ["green"] * self.N
            )

    def test_markersize(self):

        ax = self.points.plot(markersize=10)
        assert ax.collections[0].get_sizes() == [10]

        ax = self.df.plot(markersize=10)
        assert ax.collections[0].get_sizes() == [10]

        ax = self.df.plot(column="values", markersize=10)
        assert ax.collections[0].get_sizes() == [10]

        ax = self.df.plot(markersize="values")
        assert (ax.collections[0].get_sizes() == self.df["values"]).all()

        ax = self.df.plot(column="values", markersize="values")
        assert (ax.collections[0].get_sizes() == self.df["values"]).all()

    def test_markerstyle(self):
        ax = self.df2.plot(marker="+")
        expected = _style_to_vertices("+")
        np.testing.assert_array_equal(
            expected, ax.collections[0].get_paths()[0].vertices
        )

    def test_style_kwargs(self):

        ax = self.points.plot(edgecolors="k")
        assert (ax.collections[0].get_edgecolor() == [0, 0, 0, 1]).all()

    def test_style_kwargs_alpha(self):
        ax = self.df.plot(alpha=0.7)
        np.testing.assert_array_equal([0.7], ax.collections[0].get_alpha())
        with pytest.raises(TypeError):  # no list allowed for alpha
            ax = self.df.plot(alpha=[0.7, 0.2])

    def test_legend(self):
        with warnings.catch_warnings(record=True) as _:  # don't print warning
            # legend ignored if color is given.
            ax = self.df.plot(column="values", color="green", legend=True)
            assert len(ax.get_figure().axes) == 1  # no separate legend axis

        # legend ignored if no column is given.
        ax = self.df.plot(legend=True)
        assert len(ax.get_figure().axes) == 1  # no separate legend axis

        # # Continuous legend
        # the colorbar matches the Point colors
        ax = self.df.plot(column="values", cmap="RdYlGn", legend=True)
        point_colors = ax.collections[0].get_facecolors()
        cbar_colors = ax.get_figure().axes[1].collections[0].get_facecolors()
        # first point == bottom of colorbar
        np.testing.assert_array_equal(point_colors[0], cbar_colors[0])
        # last point == top of colorbar
        np.testing.assert_array_equal(point_colors[-1], cbar_colors[-1])

        # # Categorical legend
        # the colorbar matches the Point colors
        ax = self.df.plot(column="values", categorical=True, legend=True)
        point_colors = ax.collections[0].get_facecolors()
        cbar_colors = ax.get_legend().axes.collections[0].get_facecolors()
        # first point == bottom of colorbar
        np.testing.assert_array_equal(point_colors[0], cbar_colors[0])
        # last point == top of colorbar
        np.testing.assert_array_equal(point_colors[-1], cbar_colors[-1])

        # # Normalized legend
        # the colorbar matches the Point colors
        norm = matplotlib.colors.LogNorm(
            vmin=self.df[1:].exp.min(), vmax=self.df[1:].exp.max()
        )
        ax = self.df[1:].plot(column="exp", cmap="RdYlGn", legend=True, norm=norm)
        point_colors = ax.collections[0].get_facecolors()
        cbar_colors = ax.get_figure().axes[1].collections[0].get_facecolors()
        # first point == bottom of colorbar
        np.testing.assert_array_equal(point_colors[0], cbar_colors[0])
        # last point == top of colorbar
        np.testing.assert_array_equal(point_colors[-1], cbar_colors[-1])
        # colorbar generated proper long transition
        assert cbar_colors.shape == (256, 4)

    def test_subplots_norm(self):
        # colors of subplots are the same as for plot (norm is applied)
        cmap = matplotlib.cm.viridis_r
        norm = matplotlib.colors.Normalize(vmin=0, vmax=20)
        ax = self.df.plot(column="values", cmap=cmap, norm=norm)
        actual_colors_orig = ax.collections[0].get_facecolors()
        exp_colors = cmap(np.arange(10) / (20))
        np.testing.assert_array_equal(exp_colors, actual_colors_orig)
        fig, ax = plt.subplots()
        self.df[1:].plot(column="values", ax=ax, norm=norm, cmap=cmap)
        actual_colors_sub = ax.collections[0].get_facecolors()
        np.testing.assert_array_equal(actual_colors_orig[1], actual_colors_sub[0])

    def test_empty_plot(self):
        s = GeoSeries([])
        with pytest.warns(UserWarning):
            ax = s.plot()
        assert len(ax.collections) == 0
        df = GeoDataFrame([])
        with pytest.warns(UserWarning):
            ax = df.plot()
        assert len(ax.collections) == 0

    def test_multipoints(self):

        # MultiPoints
        ax = self.df2.plot()
        _check_colors(4, ax.collections[0].get_facecolors(), [MPL_DFT_COLOR] * 4)

        ax = self.df2.plot(column="values")
        cmap = plt.get_cmap()
        expected_colors = [cmap(0)] * self.N + [cmap(1)] * self.N
        _check_colors(2, ax.collections[0].get_facecolors(), expected_colors)

        ax = self.df2.plot(color=["r", "b"])
        # colors are repeated for all components within a MultiPolygon
        _check_colors(2, ax.collections[0].get_facecolors(), ["r"] * 10 + ["b"] * 10)

    def test_multipoints_alpha(self):
        ax = self.df2.plot(alpha=0.7)
        np.testing.assert_array_equal([0.7], ax.collections[0].get_alpha())
        with pytest.raises(TypeError):  # no list allowed for alpha
            ax = self.df2.plot(alpha=[0.7, 0.2])

    def test_categories(self):
        self.df["cats_object"] = ["cat1", "cat2"] * 5
        self.df["nums"] = [1, 2] * 5
        self.df["singlecat_object"] = ["cat2"] * 10
        self.df["cats"] = pd.Categorical(["cat1", "cat2"] * 5)
        self.df["singlecat"] = pd.Categorical(
            ["cat2"] * 10, categories=["cat1", "cat2"]
        )
        self.df["cats_ordered"] = pd.Categorical(
            ["cat2", "cat1"] * 5, categories=["cat2", "cat1"]
        )

        ax1 = self.df.plot("cats_object", legend=True)
        ax2 = self.df.plot("cats", legend=True)
        ax3 = self.df.plot("singlecat_object", categories=["cat1", "cat2"], legend=True)
        ax4 = self.df.plot("singlecat", legend=True)
        ax5 = self.df.plot("cats_ordered", legend=True)
        ax6 = self.df.plot("nums", categories=[1, 2], legend=True)

        point_colors1 = ax1.collections[0].get_facecolors()
        for ax in [ax2, ax3, ax4, ax5, ax6]:
            point_colors2 = ax.collections[0].get_facecolors()
            np.testing.assert_array_equal(point_colors1[1], point_colors2[1])

        legend1 = [x.get_markerfacecolor() for x in ax1.get_legend().get_lines()]
        for ax in [ax2, ax3, ax4, ax5, ax6]:
            legend2 = [x.get_markerfacecolor() for x in ax.get_legend().get_lines()]
            np.testing.assert_array_equal(legend1, legend2)

        with pytest.raises(TypeError):
            self.df.plot(column="cats_object", categories="non_list")

        with pytest.raises(
            ValueError, match="Column contains values not listed in categories."
        ):
            self.df.plot(column="cats_object", categories=["cat1"])

        with pytest.raises(
            ValueError, match="Cannot specify 'categories' when column has"
        ):
            self.df.plot(column="cats", categories=["cat1"])

    def test_misssing(self):
        self.df.loc[0, "values"] = np.nan
        ax = self.df.plot("values")
        cmap = plt.get_cmap()
        expected_colors = cmap(np.arange(self.N - 1) / (self.N - 2))
        _check_colors(self.N - 1, ax.collections[0].get_facecolors(), expected_colors)

        ax = self.df.plot("values", missing_kwds={"color": "r"})
        cmap = plt.get_cmap()
        expected_colors = cmap(np.arange(self.N - 1) / (self.N - 2))
        _check_colors(1, ax.collections[1].get_facecolors(), ["r"])
        _check_colors(self.N - 1, ax.collections[0].get_facecolors(), expected_colors)

        ax = self.df.plot(
            "values", missing_kwds={"color": "r"}, categorical=True, legend=True
        )
        _check_colors(1, ax.collections[1].get_facecolors(), ["r"])
        point_colors = ax.collections[0].get_facecolors()
        nan_color = ax.collections[1].get_facecolors()
        leg_colors = ax.get_legend().axes.collections[0].get_facecolors()
        leg_colors1 = ax.get_legend().axes.collections[1].get_facecolors()
        np.testing.assert_array_equal(point_colors[0], leg_colors[0])
        np.testing.assert_array_equal(nan_color[0], leg_colors1[0])


class TestPointZPlotting:
    def setup_method(self):
        self.N = 10
        self.points = GeoSeries(Point(i, i, i) for i in range(self.N))
        values = np.arange(self.N)
        self.df = GeoDataFrame({"geometry": self.points, "values": values})

    def test_plot(self):
        # basic test that points with z coords don't break plotting
        self.df.plot()


class TestLineStringPlotting:
    def setup_method(self):
        self.N = 10
        values = np.arange(self.N)
        self.lines = GeoSeries(
            [LineString([(0, i), (4, i + 0.5), (9, i)]) for i in range(self.N)],
            index=list("ABCDEFGHIJ"),
        )
        self.df = GeoDataFrame({"geometry": self.lines, "values": values})

        multiline1 = MultiLineString(self.lines.loc["A":"B"].values)
        multiline2 = MultiLineString(self.lines.loc["C":"D"].values)
        self.df2 = GeoDataFrame(
            {"geometry": [multiline1, multiline2], "values": [0, 1]}
        )

        self.linearrings = GeoSeries(
            [LinearRing([(0, i), (4, i + 0.5), (9, i)]) for i in range(self.N)],
            index=list("ABCDEFGHIJ"),
        )
        self.df3 = GeoDataFrame({"geometry": self.linearrings, "values": values})

    def test_single_color(self):

        ax = self.lines.plot(color="green")
        _check_colors(self.N, ax.collections[0].get_colors(), ["green"] * self.N)

        ax = self.df.plot(color="green")
        _check_colors(self.N, ax.collections[0].get_colors(), ["green"] * self.N)

        ax = self.linearrings.plot(color="green")
        _check_colors(self.N, ax.collections[0].get_colors(), ["green"] * self.N)

        ax = self.df3.plot(color="green")
        _check_colors(self.N, ax.collections[0].get_colors(), ["green"] * self.N)

        # check rgba tuple GH1178
        ax = self.df.plot(color=(0.5, 0.5, 0.5, 0.5))
        _check_colors(
            self.N, ax.collections[0].get_colors(), [(0.5, 0.5, 0.5, 0.5)] * self.N
        )
        ax = self.df.plot(color=(0.5, 0.5, 0.5, 0.5))
        _check_colors(
            self.N, ax.collections[0].get_colors(), [(0.5, 0.5, 0.5, 0.5)] * self.N
        )
        with pytest.raises((TypeError, ValueError)):
            self.df.plot(color="not color")

        with warnings.catch_warnings(record=True) as _:  # don't print warning
            # 'color' overrides 'column'
            ax = self.df.plot(column="values", color="green")
            _check_colors(self.N, ax.collections[0].get_colors(), ["green"] * self.N)

    def test_style_kwargs_linestyle(self):
        # single
        for ax in [
            self.lines.plot(linestyle=":", linewidth=1),
            self.df.plot(linestyle=":", linewidth=1),
            self.df.plot(column="values", linestyle=":", linewidth=1),
        ]:
            assert [(0.0, [1.0, 1.65])] == ax.collections[0].get_linestyle()

        # tuple
        ax = self.lines.plot(linestyle=(0, (3, 10, 1, 15)), linewidth=1)
        assert [(0, [3, 10, 1, 15])] == ax.collections[0].get_linestyle()

        # multiple
        ls = [("dashed", "dotted", "dashdot", "solid")[k % 4] for k in range(self.N)]
        exp_ls = [_style_to_linestring_onoffseq(st, 1) for st in ls]
        for ax in [
            self.lines.plot(linestyle=ls, linewidth=1),
            self.lines.plot(linestyles=ls, linewidth=1),
            self.df.plot(linestyle=ls, linewidth=1),
            self.df.plot(column="values", linestyle=ls, linewidth=1),
        ]:
            np.testing.assert_array_equal(exp_ls, ax.collections[0].get_linestyle())

    def test_style_kwargs_linewidth(self):
        # single
        for ax in [
            self.lines.plot(linewidth=2),
            self.df.plot(linewidth=2),
            self.df.plot(column="values", linewidth=2),
        ]:
            np.testing.assert_array_equal([2], ax.collections[0].get_linewidths())

        # multiple
        lw = [(0, 1, 2, 5.5, 10)[k % 5] for k in range(self.N)]
        for ax in [
            self.lines.plot(linewidth=lw),
            self.lines.plot(linewidths=lw),
            self.df.plot(linewidth=lw),
            self.df.plot(column="values", linewidth=lw),
        ]:
            np.testing.assert_array_equal(lw, ax.collections[0].get_linewidths())

    def test_style_kwargs_alpha(self):
        ax = self.df.plot(alpha=0.7)
        np.testing.assert_array_equal([0.7], ax.collections[0].get_alpha())
        with pytest.raises(TypeError):  # no list allowed for alpha
            ax = self.df.plot(alpha=[0.7, 0.2])

    def test_subplots_norm(self):
        # colors of subplots are the same as for plot (norm is applied)
        cmap = matplotlib.cm.viridis_r
        norm = matplotlib.colors.Normalize(vmin=0, vmax=20)
        ax = self.df.plot(column="values", cmap=cmap, norm=norm)
        actual_colors_orig = ax.collections[0].get_edgecolors()
        exp_colors = cmap(np.arange(10) / (20))
        np.testing.assert_array_equal(exp_colors, actual_colors_orig)
        fig, ax = plt.subplots()
        self.df[1:].plot(column="values", ax=ax, norm=norm, cmap=cmap)
        actual_colors_sub = ax.collections[0].get_edgecolors()
        np.testing.assert_array_equal(actual_colors_orig[1], actual_colors_sub[0])

    def test_multilinestrings(self):

        # MultiLineStrings
        ax = self.df2.plot()
        assert len(ax.collections[0].get_paths()) == 4
        _check_colors(4, ax.collections[0].get_facecolors(), [MPL_DFT_COLOR] * 4)

        ax = self.df2.plot("values")
        cmap = plt.get_cmap(lut=2)
        # colors are repeated for all components within a MultiLineString
        expected_colors = [cmap(0), cmap(0), cmap(1), cmap(1)]
        _check_colors(4, ax.collections[0].get_facecolors(), expected_colors)

        ax = self.df2.plot(color=["r", "b"])
        # colors are repeated for all components within a MultiLineString
        _check_colors(4, ax.collections[0].get_facecolors(), ["r", "r", "b", "b"])


class TestPolygonPlotting:
    def setup_method(self):

        t1 = Polygon([(0, 0), (1, 0), (1, 1)])
        t2 = Polygon([(1, 0), (2, 0), (2, 1)])
        self.polys = GeoSeries([t1, t2], index=list("AB"))
        self.df = GeoDataFrame({"geometry": self.polys, "values": [0, 1]})

        multipoly1 = MultiPolygon([t1, t2])
        multipoly2 = rotate(multipoly1, 180)
        self.df2 = GeoDataFrame(
            {"geometry": [multipoly1, multipoly2], "values": [0, 1]}
        )

        t3 = Polygon([(2, 0), (3, 0), (3, 1)])
        df_nan = GeoDataFrame({"geometry": t3, "values": [np.nan]})
        self.df3 = self.df.append(df_nan)

    def test_single_color(self):

        ax = self.polys.plot(color="green")
        _check_colors(2, ax.collections[0].get_facecolors(), ["green"] * 2)
        # color only sets facecolor
        _check_colors(2, ax.collections[0].get_edgecolors(), ["k"] * 2)

        ax = self.df.plot(color="green")
        _check_colors(2, ax.collections[0].get_facecolors(), ["green"] * 2)
        _check_colors(2, ax.collections[0].get_edgecolors(), ["k"] * 2)

        # check rgba tuple GH1178
        ax = self.df.plot(color=(0.5, 0.5, 0.5))
        _check_colors(2, ax.collections[0].get_facecolors(), [(0.5, 0.5, 0.5)] * 2)
        ax = self.df.plot(color=(0.5, 0.5, 0.5, 0.5))
        _check_colors(2, ax.collections[0].get_facecolors(), [(0.5, 0.5, 0.5, 0.5)] * 2)
        with pytest.raises((TypeError, ValueError)):
            self.df.plot(color="not color")

        with warnings.catch_warnings(record=True) as _:  # don't print warning
            # 'color' overrides 'values'
            ax = self.df.plot(column="values", color="green")
            _check_colors(2, ax.collections[0].get_facecolors(), ["green"] * 2)

    def test_vmin_vmax(self):
        # when vmin == vmax, all polygons should be the same color

        # non-categorical
        ax = self.df.plot(column="values", categorical=False, vmin=0, vmax=0)
        actual_colors = ax.collections[0].get_facecolors()
        np.testing.assert_array_equal(actual_colors[0], actual_colors[1])

        # categorical
        ax = self.df.plot(column="values", categorical=True, vmin=0, vmax=0)
        actual_colors = ax.collections[0].get_facecolors()
        np.testing.assert_array_equal(actual_colors[0], actual_colors[1])

        # vmin vmax set correctly for array with NaN (GitHub issue 877)
        ax = self.df3.plot(column="values")
        actual_colors = ax.collections[0].get_facecolors()
        assert np.any(np.not_equal(actual_colors[0], actual_colors[1]))

    def test_style_kwargs_color(self):

        # facecolor overrides default cmap when color is not set
        ax = self.polys.plot(facecolor="k")
        _check_colors(2, ax.collections[0].get_facecolors(), ["k"] * 2)

        # facecolor overrides more general-purpose color when both are set
        ax = self.polys.plot(color="red", facecolor="k")
        # TODO with new implementation, color overrides facecolor
        # _check_colors(2, ax.collections[0], ['k']*2, alpha=0.5)

        # edgecolor
        ax = self.polys.plot(edgecolor="red")
        np.testing.assert_array_equal(
            [(1, 0, 0, 1)], ax.collections[0].get_edgecolors()
        )

        ax = self.df.plot("values", edgecolor="red")
        np.testing.assert_array_equal(
            [(1, 0, 0, 1)], ax.collections[0].get_edgecolors()
        )

        # alpha sets both edge and face
        ax = self.polys.plot(facecolor="g", edgecolor="r", alpha=0.4)
        _check_colors(2, ax.collections[0].get_facecolors(), ["g"] * 2, alpha=0.4)
        _check_colors(2, ax.collections[0].get_edgecolors(), ["r"] * 2, alpha=0.4)

        # check rgba tuple GH1178 for face and edge
        ax = self.df.plot(facecolor=(0.5, 0.5, 0.5), edgecolor=(0.4, 0.5, 0.6))
        _check_colors(2, ax.collections[0].get_facecolors(), [(0.5, 0.5, 0.5)] * 2)
        _check_colors(2, ax.collections[0].get_edgecolors(), [(0.4, 0.5, 0.6)] * 2)

        ax = self.df.plot(
            facecolor=(0.5, 0.5, 0.5, 0.5), edgecolor=(0.4, 0.5, 0.6, 0.5)
        )
        _check_colors(2, ax.collections[0].get_facecolors(), [(0.5, 0.5, 0.5, 0.5)] * 2)
        _check_colors(2, ax.collections[0].get_edgecolors(), [(0.4, 0.5, 0.6, 0.5)] * 2)

    def test_style_kwargs_linestyle(self):
        #   single
        ax = self.df.plot(linestyle=":", linewidth=1)
        assert [(0.0, [1.0, 1.65])] == ax.collections[0].get_linestyle()

        # tuple
        ax = self.df.plot(linestyle=(0, (3, 10, 1, 15)), linewidth=1)
        assert [(0, [3, 10, 1, 15])] == ax.collections[0].get_linestyle()

        #   multiple
        ls = ["dashed", "dotted"]
        exp_ls = [_style_to_linestring_onoffseq(st, 1) for st in ls]
        for ax in [
            self.df.plot(linestyle=ls, linewidth=1),
            self.df.plot(linestyles=ls, linewidth=1),
        ]:
            assert exp_ls == ax.collections[0].get_linestyle()

    def test_style_kwargs_linewidth(self):
        #   single
        ax = self.df.plot(linewidth=2)
        np.testing.assert_array_equal([2], ax.collections[0].get_linewidths())
        #   multiple
        for ax in [self.df.plot(linewidth=[2, 4]), self.df.plot(linewidths=[2, 4])]:
            np.testing.assert_array_equal([2, 4], ax.collections[0].get_linewidths())

        # alpha
        ax = self.df.plot(alpha=0.7)
        np.testing.assert_array_equal([0.7], ax.collections[0].get_alpha())
        with pytest.raises(TypeError):  # no list allowed for alpha
            ax = self.df.plot(alpha=[0.7, 0.2])

    def test_legend_kwargs(self):

        ax = self.df.plot(
            column="values",
            categorical=True,
            legend=True,
            legend_kwds={"frameon": False},
        )
        assert ax.get_legend().get_frame_on() is False

    def test_colorbar_kwargs(self):
        # Test if kwargs are passed to colorbar

        label_txt = "colorbar test"

        ax = self.df.plot(
            column="values",
            categorical=False,
            legend=True,
            legend_kwds={"label": label_txt},
        )

        assert ax.get_figure().axes[1].get_ylabel() == label_txt

        ax = self.df.plot(
            column="values",
            categorical=False,
            legend=True,
            legend_kwds={"label": label_txt, "orientation": "horizontal"},
        )

        assert ax.get_figure().axes[1].get_xlabel() == label_txt

    def test_fmt_ignore(self):
        # test if fmt is removed if scheme is not passed (it would raise Error)
        # GH #1253

        self.df.plot(
            column="values",
            categorical=True,
            legend=True,
            legend_kwds={"fmt": "{:.0f}"},
        )

        self.df.plot(column="values", legend=True, legend_kwds={"fmt": "{:.0f}"})

    def test_multipolygons_color(self):

        # MultiPolygons
        ax = self.df2.plot()
        assert len(ax.collections[0].get_paths()) == 4
        _check_colors(4, ax.collections[0].get_facecolors(), [MPL_DFT_COLOR] * 4)

        ax = self.df2.plot("values")
        cmap = plt.get_cmap(lut=2)
        # colors are repeated for all components within a MultiPolygon
        expected_colors = [cmap(0), cmap(0), cmap(1), cmap(1)]
        _check_colors(4, ax.collections[0].get_facecolors(), expected_colors)

        ax = self.df2.plot(color=["r", "b"])
        # colors are repeated for all components within a MultiPolygon
        _check_colors(4, ax.collections[0].get_facecolors(), ["r", "r", "b", "b"])

    def test_multipolygons_linestyle(self):
        # single
        ax = self.df2.plot(linestyle=":", linewidth=1)
        assert [(0.0, [1.0, 1.65])] == ax.collections[0].get_linestyle()

        # tuple
        ax = self.df2.plot(linestyle=(0, (3, 10, 1, 15)), linewidth=1)
        assert [(0, [3, 10, 1, 15])] == ax.collections[0].get_linestyle()

        # multiple
        ls = ["dashed", "dotted"]
        exp_ls = [_style_to_linestring_onoffseq(st, 1) for st in ls for i in range(2)]
        for ax in [
            self.df2.plot(linestyle=ls, linewidth=1),
            self.df2.plot(linestyles=ls, linewidth=1),
        ]:
            assert exp_ls == ax.collections[0].get_linestyle()

    def test_multipolygons_linewidth(self):
        # single
        ax = self.df2.plot(linewidth=2)
        np.testing.assert_array_equal([2], ax.collections[0].get_linewidths())

        # multiple
        for ax in [self.df2.plot(linewidth=[2, 4]), self.df2.plot(linewidths=[2, 4])]:
            np.testing.assert_array_equal(
                [2, 2, 4, 4], ax.collections[0].get_linewidths()
            )

    def test_multipolygons_alpha(self):
        ax = self.df2.plot(alpha=0.7)
        np.testing.assert_array_equal([0.7], ax.collections[0].get_alpha())
        with pytest.raises(TypeError):  # no list allowed for alpha
            ax = self.df2.plot(alpha=[0.7, 0.2])

    def test_subplots_norm(self):
        # colors of subplots are the same as for plot (norm is applied)
        cmap = matplotlib.cm.viridis_r
        norm = matplotlib.colors.Normalize(vmin=0, vmax=10)
        ax = self.df.plot(column="values", cmap=cmap, norm=norm)
        actual_colors_orig = ax.collections[0].get_facecolors()
        exp_colors = cmap(np.arange(2) / (10))
        np.testing.assert_array_equal(exp_colors, actual_colors_orig)
        fig, ax = plt.subplots()
        self.df[1:].plot(column="values", ax=ax, norm=norm, cmap=cmap)
        actual_colors_sub = ax.collections[0].get_facecolors()
        np.testing.assert_array_equal(actual_colors_orig[1], actual_colors_sub[0])


class TestPolygonZPlotting:
    def setup_method(self):

        t1 = Polygon([(0, 0, 0), (1, 0, 0), (1, 1, 1)])
        t2 = Polygon([(1, 0, 0), (2, 0, 0), (2, 1, 1)])
        self.polys = GeoSeries([t1, t2], index=list("AB"))
        self.df = GeoDataFrame({"geometry": self.polys, "values": [0, 1]})

        multipoly1 = MultiPolygon([t1, t2])
        multipoly2 = rotate(multipoly1, 180)
        self.df2 = GeoDataFrame(
            {"geometry": [multipoly1, multipoly2], "values": [0, 1]}
        )

    def test_plot(self):
        # basic test that points with z coords don't break plotting
        self.df.plot()


class TestGeometryCollectionPlotting:
    def setup_method(self):
        coll1 = GeometryCollection(
            [
                Polygon([(1, 0), (2, 0), (2, 1)]),
                MultiLineString([((0.5, 0.5), (1, 1)), ((1, 0.5), (1.5, 1))]),
            ]
        )
        coll2 = GeometryCollection(
            [Point(0.75, 0.25), Polygon([(2, 2), (3, 2), (2, 3)])]
        )

        self.series = GeoSeries([coll1, coll2])
        self.df = GeoDataFrame({"geometry": self.series, "values": [1, 2]})

    def test_colors(self):
        # default uniform color
        ax = self.series.plot()
        _check_colors(1, ax.collections[0].get_facecolors(), [MPL_DFT_COLOR])  # poly
        _check_colors(2, ax.collections[1].get_edgecolors(), [MPL_DFT_COLOR])  # line
        _check_colors(2, ax.collections[2].get_facecolors(), [MPL_DFT_COLOR])  # point

    def test_values(self):
        ax = self.df.plot("values")
        cmap = plt.get_cmap()
        exp_colors = cmap(np.arange(2) / 1)
        _check_colors(1, ax.collections[0].get_facecolors(), exp_colors)  # poly
        _check_colors(2, ax.collections[1].get_edgecolors(), [exp_colors[0]])  # line
        _check_colors(2, ax.collections[2].get_facecolors(), [exp_colors[1]])  # point


class TestNonuniformGeometryPlotting:
    def setup_method(self):
        pytest.importorskip("matplotlib", "1.5.0")

        poly = Polygon([(1, 0), (2, 0), (2, 1)])
        line = LineString([(0.5, 0.5), (1, 1), (1, 0.5), (1.5, 1)])
        point = Point(0.75, 0.25)
        self.series = GeoSeries([poly, line, point])
        self.df = GeoDataFrame({"geometry": self.series, "values": [1, 2, 3]})

    def test_colors(self):
        # default uniform color
        ax = self.series.plot()
        _check_colors(1, ax.collections[0].get_facecolors(), [MPL_DFT_COLOR])
        _check_colors(1, ax.collections[1].get_edgecolors(), [MPL_DFT_COLOR])
        _check_colors(1, ax.collections[2].get_facecolors(), [MPL_DFT_COLOR])

        # colormap: different colors
        ax = self.series.plot(cmap="RdYlGn")
        cmap = plt.get_cmap("RdYlGn")
        exp_colors = cmap(np.arange(3) / (3 - 1))
        _check_colors(1, ax.collections[0].get_facecolors(), [exp_colors[0]])
        _check_colors(1, ax.collections[1].get_edgecolors(), [exp_colors[1]])
        _check_colors(1, ax.collections[2].get_facecolors(), [exp_colors[2]])

    def test_style_kwargs(self):
        ax = self.series.plot(markersize=10)
        assert ax.collections[2].get_sizes() == [10]
        ax = self.df.plot(markersize=10)
        assert ax.collections[2].get_sizes() == [10]

    def test_style_kwargs_linestyle(self):
        # single
        for ax in [
            self.series.plot(linestyle=":", linewidth=1),
            self.df.plot(linestyle=":", linewidth=1),
        ]:
            assert [(0.0, [1.0, 1.65])] == ax.collections[0].get_linestyle()

        # tuple
        ax = self.series.plot(linestyle=(0, (3, 10, 1, 15)), linewidth=1)
        assert [(0, [3, 10, 1, 15])] == ax.collections[0].get_linestyle()

    @pytest.mark.skip(
        reason="array-like style_kwds not supported for mixed geometry types (#1379)"
    )
    def test_style_kwargs_linestyle_listlike(self):
        # multiple
        ls = ["solid", "dotted", "dashdot"]
        exp_ls = [_style_to_linestring_onoffseq(style, 1) for style in ls]
        for ax in [
            self.series.plot(linestyle=ls, linewidth=1),
            self.series.plot(linestyles=ls, linewidth=1),
            self.df.plot(linestyles=ls, linewidth=1),
        ]:
            np.testing.assert_array_equal(exp_ls, ax.collections[0].get_linestyle())

    def test_style_kwargs_linewidth(self):
        # single
        ax = self.df.plot(linewidth=2)
        np.testing.assert_array_equal([2], ax.collections[0].get_linewidths())

    @pytest.mark.skip(
        reason="array-like style_kwds not supported for mixed geometry types (#1379)"
    )
    def test_style_kwargs_linewidth_listlike(self):
        # multiple
        for ax in [
            self.series.plot(linewidths=[2, 4, 5.5]),
            self.series.plot(linewidths=[2, 4, 5.5]),
            self.df.plot(linewidths=[2, 4, 5.5]),
        ]:
            np.testing.assert_array_equal(
                [2, 4, 5.5], ax.collections[0].get_linewidths()
            )

    def test_style_kwargs_alpha(self):
        ax = self.df.plot(alpha=0.7)
        np.testing.assert_array_equal([0.7], ax.collections[0].get_alpha())
        with pytest.raises(TypeError):  # no list allowed for alpha
            ax = self.df.plot(alpha=[0.7, 0.2, 0.9])


class TestGeographicAspect:
    def setup_class(self):
        pth = get_path("naturalearth_lowres")
        df = read_file(pth)
        self.north = df.loc[df.continent == "North America"]
        self.north_proj = self.north.to_crs("ESRI:102008")
        bounds = self.north.total_bounds
        y_coord = np.mean([bounds[1], bounds[3]])
        self.exp = 1 / np.cos(y_coord * np.pi / 180)

    def test_auto(self):
        ax = self.north.geometry.plot()
        assert ax.get_aspect() == self.exp
        ax2 = self.north_proj.geometry.plot()
        assert ax2.get_aspect() in ["equal", 1.0]
        ax = self.north.plot()
        assert ax.get_aspect() == self.exp
        ax2 = self.north_proj.plot()
        assert ax2.get_aspect() in ["equal", 1.0]
        ax3 = self.north.plot("pop_est")
        assert ax3.get_aspect() == self.exp
        ax4 = self.north_proj.plot("pop_est")
        assert ax4.get_aspect() in ["equal", 1.0]

    def test_manual(self):
        ax = self.north.geometry.plot(aspect="equal")
        assert ax.get_aspect() in ["equal", 1.0]
        ax2 = self.north.geometry.plot(aspect=0.5)
        assert ax2.get_aspect() == 0.5
        ax3 = self.north_proj.geometry.plot(aspect=0.5)
        assert ax3.get_aspect() == 0.5
        ax = self.north.plot(aspect="equal")
        assert ax.get_aspect() in ["equal", 1.0]
        ax2 = self.north.plot(aspect=0.5)
        assert ax2.get_aspect() == 0.5
        ax3 = self.north_proj.plot(aspect=0.5)
        assert ax3.get_aspect() == 0.5
        ax = self.north.plot("pop_est", aspect="equal")
        assert ax.get_aspect() in ["equal", 1.0]
        ax2 = self.north.plot("pop_est", aspect=0.5)
        assert ax2.get_aspect() == 0.5
        ax3 = self.north_proj.plot("pop_est", aspect=0.5)
        assert ax3.get_aspect() == 0.5


class TestMapclassifyPlotting:
    @classmethod
    def setup_class(cls):
        try:
            import mapclassify  # noqa
        except ImportError:
            pytest.importorskip("mapclassify")
        cls.classifiers = list(mapclassify.classifiers.CLASSIFIERS)
        cls.classifiers.remove("UserDefined")
        pth = get_path("naturalearth_lowres")
        cls.df = read_file(pth)
        cls.df["NEGATIVES"] = np.linspace(-10, 10, len(cls.df.index))

    def test_legend(self):
        with warnings.catch_warnings(record=True) as _:  # don't print warning
            # warning coming from scipy.stats
            ax = self.df.plot(
                column="pop_est", scheme="QUANTILES", k=3, cmap="OrRd", legend=True
            )
        labels = [t.get_text() for t in ax.get_legend().get_texts()]
        expected = [
            u"[       140.00,    5217064.00]",
            u"(   5217064.00,   19532732.33]",
            u"(  19532732.33, 1379302771.00]",
        ]
        assert labels == expected

    def test_bin_labels(self):
        ax = self.df.plot(
            column="pop_est",
            scheme="QUANTILES",
            k=3,
            cmap="OrRd",
            legend=True,
            legend_kwds={"labels": ["foo", "bar", "baz"]},
        )
        labels = [t.get_text() for t in ax.get_legend().get_texts()]
        expected = ["foo", "bar", "baz"]
        assert labels == expected

    def test_invalid_labels_length(self):
        with pytest.raises(ValueError):
            self.df.plot(
                column="pop_est",
                scheme="QUANTILES",
                k=3,
                cmap="OrRd",
                legend=True,
                legend_kwds={"labels": ["foo", "bar"]},
            )

    def test_negative_legend(self):
        ax = self.df.plot(
            column="NEGATIVES", scheme="FISHER_JENKS", k=3, cmap="OrRd", legend=True
        )
        labels = [t.get_text() for t in ax.get_legend().get_texts()]
        expected = [u"[-10.00,  -3.41]", u"( -3.41,   3.30]", u"(  3.30,  10.00]"]
        assert labels == expected

    def test_fmt(self):
        ax = self.df.plot(
            column="NEGATIVES",
            scheme="FISHER_JENKS",
            k=3,
            cmap="OrRd",
            legend=True,
            legend_kwds={"fmt": "{:.0f}"},
        )
        labels = [t.get_text() for t in ax.get_legend().get_texts()]
        expected = [u"[-10,  -3]", u"( -3,   3]", u"(  3,  10]"]
        assert labels == expected

    @pytest.mark.parametrize("scheme", ["FISHER_JENKS", "FISHERJENKS"])
    def test_scheme_name_compat(self, scheme):
        ax = self.df.plot(column="NEGATIVES", scheme=scheme, k=3, legend=True)
        assert len(ax.get_legend().get_texts()) == 3

    def test_schemes(self):
        # test if all available classifiers pass
        for scheme in self.classifiers:
            self.df.plot(column="pop_est", scheme=scheme, legend=True)

    def test_classification_kwds(self):
        ax = self.df.plot(
            column="pop_est",
            scheme="percentiles",
            k=3,
            classification_kwds={"pct": [50, 100]},
            cmap="OrRd",
            legend=True,
        )
        labels = [t.get_text() for t in ax.get_legend().get_texts()]
        expected = ["[       140.00,    9961396.00]", "(   9961396.00, 1379302771.00]"]
        assert labels == expected

    def test_invalid_scheme(self):
        with pytest.raises(ValueError):
            scheme = "invalid_scheme_*#&)(*#"
            self.df.plot(
                column="gdp_md_est", scheme=scheme, k=3, cmap="OrRd", legend=True
            )

    def test_cax_legend_passing(self):
        """Pass a 'cax' argument to 'df.plot(.)', that is valid only if 'ax' is
        passed as well (if not, a new figure is created ad hoc, and 'cax' is
        ignored)
        """
        ax = plt.axes()
        from mpl_toolkits.axes_grid1 import make_axes_locatable

        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.1)
        with pytest.raises(ValueError):
            ax = self.df.plot(column="pop_est", cmap="OrRd", legend=True, cax=cax)

    def test_cax_legend_height(self):
        """Pass a cax argument to 'df.plot(.)', the legend location must be
        aligned with those of main plot
        """
        # base case
        with warnings.catch_warnings(record=True) as _:  # don't print warning
            ax = self.df.plot(column="pop_est", cmap="OrRd", legend=True)
        plot_height = ax.get_figure().get_axes()[0].get_position().height
        legend_height = ax.get_figure().get_axes()[1].get_position().height
        assert abs(plot_height - legend_height) >= 1e-6
        # fix heights with cax argument
        ax2 = plt.axes()
        from mpl_toolkits.axes_grid1 import make_axes_locatable

        divider = make_axes_locatable(ax2)
        cax = divider.append_axes("right", size="5%", pad=0.1)
        with warnings.catch_warnings(record=True) as _:
            ax2 = self.df.plot(
                column="pop_est", cmap="OrRd", legend=True, cax=cax, ax=ax2
            )
        plot_height = ax2.get_figure().get_axes()[0].get_position().height
        legend_height = ax2.get_figure().get_axes()[1].get_position().height
        assert abs(plot_height - legend_height) < 1e-6


class TestPlotCollections:
    def setup_method(self):
        self.N = 3
        self.values = np.arange(self.N)
        self.points = GeoSeries(Point(i, i) for i in range(self.N))
        self.lines = GeoSeries(
            [LineString([(0, i), (4, i + 0.5), (9, i)]) for i in range(self.N)]
        )
        self.polygons = GeoSeries(
            [Polygon([(0, i), (4, i + 0.5), (9, i)]) for i in range(self.N)]
        )

    def test_points(self):
        # failing with matplotlib 1.4.3 (edge stays black even when specified)
        pytest.importorskip("matplotlib", "1.5.0")

        from geopandas.plotting import _plot_point_collection, plot_point_collection
        from matplotlib.collections import PathCollection

        fig, ax = plt.subplots()
        coll = _plot_point_collection(ax, self.points)
        assert isinstance(coll, PathCollection)
        ax.cla()

        # default: single default matplotlib color
        coll = _plot_point_collection(ax, self.points)
        _check_colors(self.N, coll.get_facecolors(), [MPL_DFT_COLOR] * self.N)
        # edgecolor depends on matplotlib version
        # _check_colors(self.N, coll.get_edgecolors(), [MPL_DFT_COLOR]*self.N)
        ax.cla()

        # specify single other color
        coll = _plot_point_collection(ax, self.points, color="g")
        _check_colors(self.N, coll.get_facecolors(), ["g"] * self.N)
        _check_colors(self.N, coll.get_edgecolors(), ["g"] * self.N)
        ax.cla()

        # specify edgecolor/facecolor
        coll = _plot_point_collection(ax, self.points, facecolor="g", edgecolor="r")
        _check_colors(self.N, coll.get_facecolors(), ["g"] * self.N)
        _check_colors(self.N, coll.get_edgecolors(), ["r"] * self.N)
        ax.cla()

        # list of colors
        coll = _plot_point_collection(ax, self.points, color=["r", "g", "b"])
        _check_colors(self.N, coll.get_facecolors(), ["r", "g", "b"])
        _check_colors(self.N, coll.get_edgecolors(), ["r", "g", "b"])
        ax.cla()

        coll = _plot_point_collection(
            ax,
            self.points,
            color=[(0.5, 0.5, 0.5, 0.5), (0.1, 0.2, 0.3, 0.5), (0.4, 0.5, 0.6, 0.5)],
        )
        _check_colors(
            self.N,
            coll.get_facecolors(),
            [(0.5, 0.5, 0.5, 0.5), (0.1, 0.2, 0.3, 0.5), (0.4, 0.5, 0.6, 0.5)],
        )
        _check_colors(
            self.N,
            coll.get_edgecolors(),
            [(0.5, 0.5, 0.5, 0.5), (0.1, 0.2, 0.3, 0.5), (0.4, 0.5, 0.6, 0.5)],
        )
        ax.cla()

        # not a color
        with pytest.raises((TypeError, ValueError)):
            _plot_point_collection(ax, self.points, color="not color")

        # check DeprecationWarning
        with pytest.warns(DeprecationWarning):
            plot_point_collection(ax, self.points)

    def test_points_values(self):
        from geopandas.plotting import _plot_point_collection

        # default colormap
        fig, ax = plt.subplots()
        coll = _plot_point_collection(ax, self.points, self.values)
        fig.canvas.draw_idle()
        cmap = plt.get_cmap()
        expected_colors = cmap(np.arange(self.N) / (self.N - 1))
        _check_colors(self.N, coll.get_facecolors(), expected_colors)
        # edgecolor depends on matplotlib version
        # _check_colors(self.N, coll.get_edgecolors(), expected_colors)

    def test_linestrings(self):
        from geopandas.plotting import (
            _plot_linestring_collection,
            plot_linestring_collection,
        )
        from matplotlib.collections import LineCollection

        fig, ax = plt.subplots()
        coll = _plot_linestring_collection(ax, self.lines)
        assert isinstance(coll, LineCollection)
        ax.cla()

        # default: single default matplotlib color
        coll = _plot_linestring_collection(ax, self.lines)
        _check_colors(self.N, coll.get_color(), [MPL_DFT_COLOR] * self.N)
        ax.cla()

        # specify single other color
        coll = _plot_linestring_collection(ax, self.lines, color="g")
        _check_colors(self.N, coll.get_colors(), ["g"] * self.N)
        ax.cla()

        # specify edgecolor / facecolor
        coll = _plot_linestring_collection(ax, self.lines, facecolor="g", edgecolor="r")
        _check_colors(self.N, coll.get_facecolors(), ["g"] * self.N)
        _check_colors(self.N, coll.get_edgecolors(), ["r"] * self.N)
        ax.cla()

        # list of colors
        coll = _plot_linestring_collection(ax, self.lines, color=["r", "g", "b"])
        _check_colors(self.N, coll.get_colors(), ["r", "g", "b"])
        ax.cla()

        coll = _plot_linestring_collection(
            ax,
            self.lines,
            color=[(0.5, 0.5, 0.5, 0.5), (0.1, 0.2, 0.3, 0.5), (0.4, 0.5, 0.6, 0.5)],
        )
        _check_colors(
            self.N,
            coll.get_colors(),
            [(0.5, 0.5, 0.5, 0.5), (0.1, 0.2, 0.3, 0.5), (0.4, 0.5, 0.6, 0.5)],
        )
        ax.cla()

        # pass through of kwargs
        coll = _plot_linestring_collection(ax, self.lines, linestyle="--", linewidth=1)
        exp_ls = _style_to_linestring_onoffseq("dashed", 1)
        res_ls = coll.get_linestyle()[0]
        assert res_ls[0] == exp_ls[0]
        assert res_ls[1] == exp_ls[1]
        ax.cla()

        # not a color
        with pytest.raises((TypeError, ValueError)):
            _plot_linestring_collection(ax, self.lines, color="not color")
        # check DeprecationWarning
        with pytest.warns(DeprecationWarning):
            plot_linestring_collection(ax, self.lines)

    def test_linestrings_values(self):
        from geopandas.plotting import _plot_linestring_collection

        fig, ax = plt.subplots()

        # default colormap
        coll = _plot_linestring_collection(ax, self.lines, self.values)
        fig.canvas.draw_idle()
        cmap = plt.get_cmap()
        expected_colors = cmap(np.arange(self.N) / (self.N - 1))
        _check_colors(self.N, coll.get_color(), expected_colors)
        ax.cla()

        # specify colormap
        coll = _plot_linestring_collection(ax, self.lines, self.values, cmap="RdBu")
        fig.canvas.draw_idle()
        cmap = plt.get_cmap("RdBu")
        expected_colors = cmap(np.arange(self.N) / (self.N - 1))
        _check_colors(self.N, coll.get_color(), expected_colors)
        ax.cla()

        # specify vmin/vmax
        coll = _plot_linestring_collection(ax, self.lines, self.values, vmin=3, vmax=5)
        fig.canvas.draw_idle()
        cmap = plt.get_cmap()
        expected_colors = cmap([0])
        _check_colors(self.N, coll.get_color(), expected_colors)
        ax.cla()

    def test_polygons(self):
        from geopandas.plotting import _plot_polygon_collection, plot_polygon_collection
        from matplotlib.collections import PatchCollection

        fig, ax = plt.subplots()
        coll = _plot_polygon_collection(ax, self.polygons)
        assert isinstance(coll, PatchCollection)
        ax.cla()

        # default: single default matplotlib color
        coll = _plot_polygon_collection(ax, self.polygons)
        _check_colors(self.N, coll.get_facecolor(), [MPL_DFT_COLOR] * self.N)
        _check_colors(self.N, coll.get_edgecolor(), ["k"] * self.N)
        ax.cla()

        # default: color sets both facecolor and edgecolor
        coll = _plot_polygon_collection(ax, self.polygons, color="g")
        _check_colors(self.N, coll.get_facecolor(), ["g"] * self.N)
        _check_colors(self.N, coll.get_edgecolor(), ["g"] * self.N)
        ax.cla()

        # default: color can be passed as a list
        coll = _plot_polygon_collection(ax, self.polygons, color=["g", "b", "r"])
        _check_colors(self.N, coll.get_facecolor(), ["g", "b", "r"])
        _check_colors(self.N, coll.get_edgecolor(), ["g", "b", "r"])
        ax.cla()

        coll = _plot_polygon_collection(
            ax,
            self.polygons,
            color=[(0.5, 0.5, 0.5, 0.5), (0.1, 0.2, 0.3, 0.5), (0.4, 0.5, 0.6, 0.5)],
        )
        _check_colors(
            self.N,
            coll.get_facecolor(),
            [(0.5, 0.5, 0.5, 0.5), (0.1, 0.2, 0.3, 0.5), (0.4, 0.5, 0.6, 0.5)],
        )
        _check_colors(
            self.N,
            coll.get_edgecolor(),
            [(0.5, 0.5, 0.5, 0.5), (0.1, 0.2, 0.3, 0.5), (0.4, 0.5, 0.6, 0.5)],
        )
        ax.cla()

        # only setting facecolor keeps default for edgecolor
        coll = _plot_polygon_collection(ax, self.polygons, facecolor="g")
        _check_colors(self.N, coll.get_facecolor(), ["g"] * self.N)
        _check_colors(self.N, coll.get_edgecolor(), ["k"] * self.N)
        ax.cla()

        # custom facecolor and edgecolor
        coll = _plot_polygon_collection(ax, self.polygons, facecolor="g", edgecolor="r")
        _check_colors(self.N, coll.get_facecolor(), ["g"] * self.N)
        _check_colors(self.N, coll.get_edgecolor(), ["r"] * self.N)
        ax.cla()

        # not a color
        with pytest.raises((TypeError, ValueError)):
            _plot_polygon_collection(ax, self.polygons, color="not color")
        # check DeprecationWarning
        with pytest.warns(DeprecationWarning):
            plot_polygon_collection(ax, self.polygons)

    def test_polygons_values(self):
        from geopandas.plotting import _plot_polygon_collection

        fig, ax = plt.subplots()

        # default colormap, edge is still black by default
        coll = _plot_polygon_collection(ax, self.polygons, self.values)
        fig.canvas.draw_idle()
        cmap = plt.get_cmap()
        exp_colors = cmap(np.arange(self.N) / (self.N - 1))
        _check_colors(self.N, coll.get_facecolor(), exp_colors)
        # edgecolor depends on matplotlib version
        # _check_colors(self.N, coll.get_edgecolor(), ['k'] * self.N)
        ax.cla()

        # specify colormap
        coll = _plot_polygon_collection(ax, self.polygons, self.values, cmap="RdBu")
        fig.canvas.draw_idle()
        cmap = plt.get_cmap("RdBu")
        exp_colors = cmap(np.arange(self.N) / (self.N - 1))
        _check_colors(self.N, coll.get_facecolor(), exp_colors)
        ax.cla()

        # specify vmin/vmax
        coll = _plot_polygon_collection(ax, self.polygons, self.values, vmin=3, vmax=5)
        fig.canvas.draw_idle()
        cmap = plt.get_cmap()
        exp_colors = cmap([0])
        _check_colors(self.N, coll.get_facecolor(), exp_colors)
        ax.cla()

        # override edgecolor
        coll = _plot_polygon_collection(ax, self.polygons, self.values, edgecolor="g")
        fig.canvas.draw_idle()
        cmap = plt.get_cmap()
        exp_colors = cmap(np.arange(self.N) / (self.N - 1))
        _check_colors(self.N, coll.get_facecolor(), exp_colors)
        _check_colors(self.N, coll.get_edgecolor(), ["g"] * self.N)
        ax.cla()


def test_column_values():
    """
    Check that the dataframe plot method returns same values with an
    input string (column in df), pd.Series, or np.array
    """
    # Build test data
    t1 = Polygon([(0, 0), (1, 0), (1, 1)])
    t2 = Polygon([(1, 0), (2, 0), (2, 1)])
    polys = GeoSeries([t1, t2], index=list("AB"))
    df = GeoDataFrame({"geometry": polys, "values": [0, 1]})

    # Test with continous values
    ax = df.plot(column="values")
    colors = ax.collections[0].get_facecolors()
    ax = df.plot(column=df["values"])
    colors_series = ax.collections[0].get_facecolors()
    np.testing.assert_array_equal(colors, colors_series)
    ax = df.plot(column=df["values"].values)
    colors_array = ax.collections[0].get_facecolors()
    np.testing.assert_array_equal(colors, colors_array)

    # Test with categorical values
    ax = df.plot(column="values", categorical=True)
    colors = ax.collections[0].get_facecolors()
    ax = df.plot(column=df["values"], categorical=True)
    colors_series = ax.collections[0].get_facecolors()
    np.testing.assert_array_equal(colors, colors_series)
    ax = df.plot(column=df["values"].values, categorical=True)
    colors_array = ax.collections[0].get_facecolors()
    np.testing.assert_array_equal(colors, colors_array)

    # Check raised error: is df rows number equal to column legth?
    with pytest.raises(ValueError, match="different number of rows"):
        ax = df.plot(column=np.array([1, 2, 3]))


def _check_colors(N, actual_colors, expected_colors, alpha=None):
    """
    Asserts that the members of `collection` match the `expected_colors`
    (in order)

    Parameters
    ----------
    N : int
        The number of geometries believed to be in collection.
        matplotlib.collection is implemented such that the number of geoms in
        `collection` doesn't have to match the number of colors assignments in
        the collection: the colors will cycle to meet the needs of the geoms.
        `N` helps us resolve this.
    collection : matplotlib.collections.Collection
        The colors of this collection's patches are read from
        `collection.get_facecolors()`
    expected_colors : sequence of RGBA tuples
    alpha : float (optional)
        If set, this alpha transparency will be applied to the
        `expected_colors`. (Any transparency on the `collection` is assumed
        to be set in its own facecolor RGBA tuples.)
    """
    import matplotlib.colors as colors

    conv = colors.colorConverter

    # Convert 2D numpy array to a list of RGBA tuples.
    actual_colors = map(tuple, actual_colors)
    all_actual_colors = list(itertools.islice(itertools.cycle(actual_colors), N))

    for actual, expected in zip(all_actual_colors, expected_colors):
        assert actual == conv.to_rgba(expected, alpha=alpha), "{} != {}".format(
            actual, conv.to_rgba(expected, alpha=alpha)
        )


def _style_to_linestring_onoffseq(linestyle, linewidth):
    """ Converts a linestyle string representation, namely one of:
            ['dashed',  'dotted', 'dashdot', 'solid'],
        documented in `Collections.set_linestyle`,
        to the form `onoffseq`.
    """
    offset, dashes = matplotlib.lines._get_dash_pattern(linestyle)
    return matplotlib.lines._scale_dashes(offset, dashes, linewidth)


def _style_to_vertices(markerstyle):
    """ Converts a markerstyle string to a path. """
    # TODO: Vertices values are twice the actual path; unclear, why.
    path = matplotlib.markers.MarkerStyle(markerstyle).get_path()
    return path.vertices / 2