summaryrefslogtreecommitdiff
path: root/silx/gui/plot/PlotWidget.py
blob: cfe39fa11e0f69787234286ce2189049ec45ba6b (plain)
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
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2004-2019 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# ###########################################################################*/
"""Qt widget providing plot API for 1D and 2D data.

The :class:`PlotWidget` implements the plot API initially provided in PyMca.
"""

from __future__ import division


__authors__ = ["V.A. Sole", "T. Vincent"]
__license__ = "MIT"
__date__ = "21/12/2018"


from collections import OrderedDict, namedtuple
from contextlib import contextmanager
import datetime as dt
import itertools
import logging

import numpy

import silx
from silx.utils.weakref import WeakMethodProxy
from silx.utils.property import classproperty
from silx.utils.deprecation import deprecated
# Import matplotlib backend here to init matplotlib our way
from .backends.BackendMatplotlib import BackendMatplotlibQt

from ..colors import Colormap
from .. import colors
from . import PlotInteraction
from . import PlotEvents
from .LimitsHistory import LimitsHistory
from . import _utils

from . import items
from .items.curve import CurveStyle
from .items.axis import TickMode  # noqa

from .. import qt
from ._utils.panzoom import ViewConstraints
from ...gui.plot._utils.dtime_ticklayout import timestamp

_logger = logging.getLogger(__name__)


_COLORDICT = colors.COLORDICT
_COLORLIST = silx.config.DEFAULT_PLOT_CURVE_COLORS

"""
Object returned when requesting the data range.
"""
_PlotDataRange = namedtuple('PlotDataRange',
                            ['x', 'y', 'yright'])


class PlotWidget(qt.QMainWindow):
    """Qt Widget providing a 1D/2D plot.

    This widget is a QMainWindow.
    This class implements the plot API initially provided in PyMca.

    Supported backends:

    - 'matplotlib' and 'mpl': Matplotlib with Qt.
    - 'opengl' and 'gl': OpenGL backend (requires PyOpenGL and OpenGL >= 2.1)
    - 'none': No backend, to run headless for testing purpose.

    :param parent: The parent of this widget or None (default).
    :param backend: The backend to use, in:
                    'matplotlib' (default), 'mpl', 'opengl', 'gl', 'none'
                    or a :class:`BackendBase.BackendBase` class
    :type backend: str or :class:`BackendBase.BackendBase`
    """

    # TODO: Can be removed for silx 0.10
    @classproperty
    @deprecated(replacement="silx.config.DEFAULT_PLOT_BACKEND", since_version="0.8", skip_backtrace_count=2)
    def DEFAULT_BACKEND(self):
        """Class attribute setting the default backend for all instances."""
        return silx.config.DEFAULT_PLOT_BACKEND

    colorList = _COLORLIST
    colorDict = _COLORDICT

    sigPlotSignal = qt.Signal(object)
    """Signal for all events of the plot.

    The signal information is provided as a dict.
    See the :ref:`plot signal documentation page <plot_signal>` for
    information about the content of the dict
    """

    sigSetKeepDataAspectRatio = qt.Signal(bool)
    """Signal emitted when plot keep aspect ratio has changed"""

    sigSetGraphGrid = qt.Signal(str)
    """Signal emitted when plot grid has changed"""

    sigSetGraphCursor = qt.Signal(bool)
    """Signal emitted when plot crosshair cursor has changed"""

    sigSetPanWithArrowKeys = qt.Signal(bool)
    """Signal emitted when pan with arrow keys has changed"""

    _sigAxesVisibilityChanged = qt.Signal(bool)
    """Signal emitted when the axes visibility changed"""

    sigContentChanged = qt.Signal(str, str, str)
    """Signal emitted when the content of the plot is changed.

    It provides the following information:

    - action: The change of the plot: 'add' or 'remove'
    - kind: The kind of primitive changed:
      'curve', 'image', 'scatter', 'histogram', 'item' or 'marker'
    - legend: The legend of the primitive changed.
    """

    sigActiveCurveChanged = qt.Signal(object, object)
    """Signal emitted when the active curve has changed.

    It provides the following information:

    - previous: The legend of the previous active curve or None
    - legend: The legend of the new active curve or None if no curve is active
    """

    sigActiveImageChanged = qt.Signal(object, object)
    """Signal emitted when the active image has changed.

    It provides the following information:

    - previous: The legend of the previous active image or None
    - legend: The legend of the new active image or None if no image is active
    """

    sigActiveScatterChanged = qt.Signal(object, object)
    """Signal emitted when the active Scatter has changed.

    It provides the following information:

    - previous: The legend of the previous active scatter or None
    - legend: The legend of the new active image or None if no image is active
    """

    sigInteractiveModeChanged = qt.Signal(object)
    """Signal emitted when the interactive mode has changed

    It provides the source as passed to :meth:`setInteractiveMode`.
    """

    sigItemAdded = qt.Signal(items.Item)
    """Signal emitted when an item was just added to the plot

    It provides the added item.
    """

    sigItemAboutToBeRemoved = qt.Signal(items.Item)
    """Signal emitted right before an item is removed from the plot.

    It provides the item that will be removed.
    """

    sigVisibilityChanged = qt.Signal(bool)
    """Signal emitted when the widget becomes visible (or invisible).
    This happens when the widget is hidden or shown.

    It provides the visible state.
    """

    def __init__(self, parent=None, backend=None):
        self._autoreplot = False
        self._dirty = False
        self._cursorInPlot = False
        self.__muteActiveItemChanged = False

        self._panWithArrowKeys = True
        self._viewConstrains = None

        super(PlotWidget, self).__init__(parent)
        if parent is not None:
            # behave as a widget
            self.setWindowFlags(qt.Qt.Widget)
        else:
            self.setWindowTitle('PlotWidget')

        self._backend = None
        self._setBackend(backend)

        self.setCallback()  # set _callback

        # Items handling
        self._content = OrderedDict()
        self._contentToUpdate = []  # Used as an OrderedSet

        self._dataRange = None

        # line types
        self._styleList = ['-', '--', '-.', ':']
        self._colorIndex = 0
        self._styleIndex = 0

        self._activeCurveSelectionMode = "atmostone"
        self._activeCurveStyle = CurveStyle(color='#000000')
        self._activeLegend = {'curve': None, 'image': None,
                              'scatter': None}

        # plot colors (updated later to sync backend)
        self._foregroundColor = 0., 0., 0., 1.
        self._gridColor = .7, .7, .7, 1.
        self._backgroundColor = 1., 1., 1., 1.
        self._dataBackgroundColor = None

        # default properties
        self._cursorConfiguration = None

        self._xAxis = items.XAxis(self)
        self._yAxis = items.YAxis(self)
        self._yRightAxis = items.YRightAxis(self, self._yAxis)

        self._grid = None
        self._graphTitle = ''

        self.setGraphTitle()
        self.setGraphXLabel()
        self.setGraphYLabel()
        self.setGraphYLabel('', axis='right')

        self.setDefaultColormap()  # Init default colormap

        self.setDefaultPlotPoints(silx.config.DEFAULT_PLOT_CURVE_SYMBOL_MODE)
        self.setDefaultPlotLines(True)

        self._limitsHistory = LimitsHistory(self)

        self._eventHandler = PlotInteraction.PlotInteraction(self)
        self._eventHandler.setInteractiveMode('zoom', color=(0., 0., 0., 1.))

        self._pressedButtons = []  # Currently pressed mouse buttons

        self._defaultDataMargins = (0., 0., 0., 0.)

        # Only activate autoreplot at the end
        # This avoids errors when loaded in Qt designer
        self._dirty = False
        self._autoreplot = True

        widget = self.getWidgetHandle()
        if widget is not None:
            self.setCentralWidget(widget)
        else:
            _logger.info("PlotWidget backend does not support widget")

        self.setFocusPolicy(qt.Qt.StrongFocus)
        self.setFocus(qt.Qt.OtherFocusReason)

        # Set default limits
        self.setGraphXLimits(0., 100.)
        self.setGraphYLimits(0., 100., axis='right')
        self.setGraphYLimits(0., 100., axis='left')

        # Sync backend colors with default ones
        self._foregroundColorsUpdated()
        self._backgroundColorsUpdated()

    def _setBackend(self, backend):
        """Setup a new backend"""
        assert(self._backend is None)

        if backend is None:
            backend = silx.config.DEFAULT_PLOT_BACKEND

        if hasattr(backend, "__call__"):
            backend = backend(self, self)

        elif hasattr(backend, "lower"):
            lowerCaseString = backend.lower()
            if lowerCaseString in ("matplotlib", "mpl"):
                backendClass = BackendMatplotlibQt
            elif lowerCaseString in ('gl', 'opengl'):
                from .backends.BackendOpenGL import BackendOpenGL
                backendClass = BackendOpenGL
            elif lowerCaseString == 'none':
                from .backends.BackendBase import BackendBase as backendClass
            else:
                raise ValueError("Backend not supported %s" % backend)
            backend = backendClass(self, self)

        else:
            raise ValueError("Backend not supported %s" % str(backend))

        self._backend = backend

    # TODO: Can be removed for silx 0.10
    @staticmethod
    @deprecated(replacement="silx.config.DEFAULT_PLOT_BACKEND", since_version="0.8", skip_backtrace_count=2)
    def setDefaultBackend(backend):
        """Set system wide default plot backend.

        .. versionadded:: 0.6

        :param backend: The backend to use, in:
                        'matplotlib' (default), 'mpl', 'opengl', 'gl', 'none'
                        or a :class:`BackendBase.BackendBase` class
        """
        silx.config.DEFAULT_PLOT_BACKEND = backend

    def _getDirtyPlot(self):
        """Return the plot dirty flag.

        If False, the plot has not changed since last replot.
        If True, the full plot need to be redrawn.
        If 'overlay', only the overlay has changed since last replot.

        It can be accessed by backend to check the dirty state.

        :return: False, True, 'overlay'
        """
        return self._dirty

    def _setDirtyPlot(self, overlayOnly=False):
        """Mark the plot as needing redraw

        :param bool overlayOnly: True to redraw only the overlay,
                                 False to redraw everything
        """
        wasDirty = self._dirty

        if not self._dirty and overlayOnly:
            self._dirty = 'overlay'
        else:
            self._dirty = True

        if self._autoreplot and not wasDirty and self.isVisible():
            self._backend.postRedisplay()

    def _foregroundColorsUpdated(self):
        """Handle change of foreground/grid color"""
        if self._gridColor is None:
            gridColor = self._foregroundColor
        else:
            gridColor = self._gridColor
        self._backend.setForegroundColors(
            self._foregroundColor, gridColor)
        self._setDirtyPlot()

    def getForegroundColor(self):
        """Returns the RGBA colors used to display the foreground of this widget

        :rtype: qt.QColor
        """
        return qt.QColor.fromRgbF(*self._foregroundColor)

    def setForegroundColor(self, color):
        """Set the foreground color of this widget.

        :param Union[List[int],List[float],QColor] color:
            The new RGB(A) color.
        """
        color = colors.rgba(color)
        if self._foregroundColor != color:
            self._foregroundColor = color
            self._foregroundColorsUpdated()

    def getGridColor(self):
        """Returns the RGBA colors used to display the grid lines

        An invalid QColor is returned if there is no grid color,
        in which case the foreground color is used.

        :rtype: qt.QColor
        """
        if self._gridColor is None:
            return qt.QColor()  # An invalid color
        else:
            return qt.QColor.fromRgbF(*self._gridColor)

    def setGridColor(self, color):
        """Set the grid lines color

        :param Union[List[int],List[float],QColor,None] color:
            The new RGB(A) color.
        """
        if isinstance(color, qt.QColor) and not color.isValid():
            color = None
        if color is not None:
            color = colors.rgba(color)
        if self._gridColor != color:
            self._gridColor = color
            self._foregroundColorsUpdated()

    def _backgroundColorsUpdated(self):
        """Handle change of background/data background color"""
        if self._dataBackgroundColor is None:
            dataBGColor = self._backgroundColor
        else:
            dataBGColor = self._dataBackgroundColor
        self._backend.setBackgroundColors(
            self._backgroundColor, dataBGColor)
        self._setDirtyPlot()

    def getBackgroundColor(self):
        """Returns the RGBA colors used to display the background of this widget.

        :rtype: qt.QColor
        """
        return qt.QColor.fromRgbF(*self._backgroundColor)

    def setBackgroundColor(self, color):
        """Set the background color of this widget.

        :param Union[List[int],List[float],QColor] color:
            The new RGB(A) color.
        """
        color = colors.rgba(color)
        if self._backgroundColor != color:
            self._backgroundColor = color
            self._backgroundColorsUpdated()

    def getDataBackgroundColor(self):
        """Returns the RGBA colors used to display the background of the plot
        view displaying the data.

        An invalid QColor is returned if there is no data background color.

        :rtype: qt.QColor
        """
        if self._dataBackgroundColor is None:
            # An invalid color
            return qt.QColor()
        else:
            return qt.QColor.fromRgbF(*self._dataBackgroundColor)

    def setDataBackgroundColor(self, color):
        """Set the background color of this widget.

        Set to None or an invalid QColor to use the background color.

        :param Union[List[int],List[float],QColor,None] color:
            The new RGB(A) color.
        """
        if isinstance(color, qt.QColor) and not color.isValid():
            color = None
        if color is not None:
            color = colors.rgba(color)
        if self._dataBackgroundColor != color:
            self._dataBackgroundColor = color
            self._backgroundColorsUpdated()

    def showEvent(self, event):
        if self._autoreplot and self._dirty:
            self._backend.postRedisplay()
        super(PlotWidget, self).showEvent(event)
        self.sigVisibilityChanged.emit(True)

    def hideEvent(self, event):
        super(PlotWidget, self).hideEvent(event)
        self.sigVisibilityChanged.emit(False)

    def _invalidateDataRange(self):
        """
        Notifies this PlotWidget instance that the range has changed
        and will have to be recomputed.
        """
        self._dataRange = None

    def _updateDataRange(self):
        """
        Recomputes the range of the data displayed on this PlotWidget.
        """
        xMin = yMinLeft = yMinRight = float('nan')
        xMax = yMaxLeft = yMaxRight = float('nan')

        for item in self._content.values():
            if item.isVisible():
                bounds = item.getBounds()
                if bounds is not None:
                    xMin = numpy.nanmin([xMin, bounds[0]])
                    xMax = numpy.nanmax([xMax, bounds[1]])
                    # Take care of right axis
                    if (isinstance(item, items.YAxisMixIn) and
                            item.getYAxis() == 'right'):
                        yMinRight = numpy.nanmin([yMinRight, bounds[2]])
                        yMaxRight = numpy.nanmax([yMaxRight, bounds[3]])
                    else:
                        yMinLeft = numpy.nanmin([yMinLeft, bounds[2]])
                        yMaxLeft = numpy.nanmax([yMaxLeft, bounds[3]])

        def lGetRange(x, y):
            return None if numpy.isnan(x) and numpy.isnan(y) else (x, y)
        xRange = lGetRange(xMin, xMax)
        yLeftRange = lGetRange(yMinLeft, yMaxLeft)
        yRightRange = lGetRange(yMinRight, yMaxRight)

        self._dataRange = _PlotDataRange(x=xRange,
                                         y=yLeftRange,
                                         yright=yRightRange)

    def getDataRange(self):
        """
        Returns this PlotWidget's data range.

        :return: a namedtuple with the following members :
                x, y (left y axis), yright. Each member is a tuple (min, max)
                or None if no data is associated with the axis.
        :rtype: namedtuple
        """
        if self._dataRange is None:
            self._updateDataRange()
        return self._dataRange

    # Content management

    @staticmethod
    def _itemKey(item):
        """Build the key of given :class:`Item` in the plot

        :param Item item: The item to make the key from
        :return: (legend, kind)
        :rtype: (str, str)
        """
        if isinstance(item, items.Curve):
            kind = 'curve'
        elif isinstance(item, items.ImageBase):
            kind = 'image'
        elif isinstance(item, items.Scatter):
            kind = 'scatter'
        elif isinstance(item, (items.Marker,
                               items.XMarker, items.YMarker)):
            kind = 'marker'
        elif isinstance(item, items.Shape):
            kind = 'item'
        elif isinstance(item, items.Histogram):
            kind = 'histogram'
        else:
            raise ValueError('Unsupported item type %s' % type(item))

        return item.getLegend(), kind

    def _add(self, item):
        """Add the given :class:`Item` to the plot.

        :param Item item: The item to append to the plot content
        """
        key = self._itemKey(item)
        if key in self._content:
            raise RuntimeError('Item already in the plot')

        # Add item to plot
        self._content[key] = item
        item._setPlot(self)
        if item.isVisible():
            self._itemRequiresUpdate(item)
        if isinstance(item, items.DATA_ITEMS):
            self._invalidateDataRange()  # TODO handle this automatically

        self._notifyContentChanged(item)
        self.sigItemAdded.emit(item)

    def _notifyContentChanged(self, item):
        legend, kind = self._itemKey(item)
        self.notify('contentChanged', action='add', kind=kind, legend=legend)

    def _remove(self, item):
        """Remove the given :class:`Item` from the plot.

        :param Item item: The item to remove from the plot content
        """
        key = self._itemKey(item)
        if key not in self._content:
            raise RuntimeError('Item not in the plot')

        self.sigItemAboutToBeRemoved.emit(item)

        legend, kind = key

        if kind in self._ACTIVE_ITEM_KINDS:
            if self._getActiveItem(kind) == item:
                # Reset active item
                self._setActiveItem(kind, None)

        # Remove item from plot
        self._content.pop(key)
        if item in self._contentToUpdate:
            self._contentToUpdate.remove(item)
        if item.isVisible():
            self._setDirtyPlot(overlayOnly=item.isOverlay())
        if item.getBounds() is not None:
            self._invalidateDataRange()
        item._removeBackendRenderer(self._backend)
        item._setPlot(None)

        if (kind == 'curve' and not self.getAllCurves(just_legend=True,
                                                      withhidden=True)):
            self._resetColorAndStyle()

        self.notify('contentChanged', action='remove',
                    kind=kind, legend=legend)

    def _itemRequiresUpdate(self, item):
        """Called by items in the plot for asynchronous update

        :param Item item: The item that required update
        """
        assert item.getPlot() == self
        # Pu item at the end of the list
        if item in self._contentToUpdate:
            self._contentToUpdate.remove(item)
        self._contentToUpdate.append(item)
        self._setDirtyPlot(overlayOnly=item.isOverlay())

    @contextmanager
    def _muteActiveItemChangedSignal(self):
        self.__muteActiveItemChanged = True
        yield
        self.__muteActiveItemChanged = False

    # Add

    # add * input arguments management:
    # If an arg is set, then use it.
    # Else:
    #     If a curve with the same legend exists, then use its arg value
    #     Else, use a default value.
    # Store used value.
    # This value is used when curve is updated either internally or by user.

    def addCurve(self, x, y, legend=None, info=None,
                 replace=False,
                 color=None, symbol=None,
                 linewidth=None, linestyle=None,
                 xlabel=None, ylabel=None, yaxis=None,
                 xerror=None, yerror=None, z=None, selectable=None,
                 fill=None, resetzoom=True,
                 histogram=None, copy=True):
        """Add a 1D curve given by x an y to the graph.

        Curves are uniquely identified by their legend.
        To add multiple curves, call :meth:`addCurve` multiple times with
        different legend argument.
        To replace an existing curve, call :meth:`addCurve` with the
        existing curve legend.
        If you want to display the curve values as an histogram see the
        histogram parameter or :meth:`addHistogram`.

        When curve parameters are not provided, if a curve with the
        same legend is displayed in the plot, its parameters are used.

        :param numpy.ndarray x: The data corresponding to the x coordinates.
          If you attempt to plot an histogram you can set edges values in x.
          In this case len(x) = len(y) + 1.
          If x contains datetime objects the XAxis tickMode is set to
          TickMode.TIME_SERIES.
        :param numpy.ndarray y: The data corresponding to the y coordinates
        :param str legend: The legend to be associated to the curve (or None)
        :param info: User-defined information associated to the curve
        :param bool replace: True (the default) to delete already existing
                             curves
        :param color: color(s) to be used
        :type color: str ("#RRGGBB") or (npoints, 4) unsigned byte array or
                     one of the predefined color names defined in colors.py
        :param str symbol: Symbol to be drawn at each (x, y) position::

            - 'o' circle
            - '.' point
            - ',' pixel
            - '+' cross
            - 'x' x-cross
            - 'd' diamond
            - 's' square
            - None (the default) to use default symbol

        :param float linewidth: The width of the curve in pixels (Default: 1).
        :param str linestyle: Type of line::

            - ' '  no line
            - '-'  solid line
            - '--' dashed line
            - '-.' dash-dot line
            - ':'  dotted line
            - None (the default) to use default line style

        :param str xlabel: Label to show on the X axis when the curve is active
                           or None to keep default axis label.
        :param str ylabel: Label to show on the Y axis when the curve is active
                           or None to keep default axis label.
        :param str yaxis: The Y axis this curve is attached to.
                          Either 'left' (the default) or 'right'
        :param xerror: Values with the uncertainties on the x values
        :type xerror: A float, or a numpy.ndarray of float32.
                      If it is an array, it can either be a 1D array of
                      same length as the data or a 2D array with 2 rows
                      of same length as the data: row 0 for positive errors,
                      row 1 for negative errors.
        :param yerror: Values with the uncertainties on the y values
        :type yerror: A float, or a numpy.ndarray of float32. See xerror.
        :param int z: Layer on which to draw the curve (default: 1)
                      This allows to control the overlay.
        :param bool selectable: Indicate if the curve can be selected.
                                (Default: True)
        :param bool fill: True to fill the curve, False otherwise (default).
        :param bool resetzoom: True (the default) to reset the zoom.
        :param str histogram: if not None then the curve will be draw as an
            histogram. The step for each values of the curve can be set to the
            left, center or right of the original x curve values.
            If histogram is not None and len(x) == len(y)+1 then x is directly
            take as edges of the histogram.
            Type of histogram::

            - None (default)
            - 'left'
            - 'right'
            - 'center'
        :param bool copy: True make a copy of the data (default),
                          False to use provided arrays.
        :returns: The key string identify this curve
        """
        # This is an histogram, use addHistogram
        if histogram is not None:
            histoLegend = self.addHistogram(histogram=y,
                                            edges=x,
                                            legend=legend,
                                            color=color,
                                            fill=fill,
                                            align=histogram,
                                            copy=copy)
            histo = self.getHistogram(histoLegend)

            histo.setInfo(info)
            if linewidth is not None:
                histo.setLineWidth(linewidth)
            if linestyle is not None:
                histo.setLineStyle(linestyle)
            if xlabel is not None:
                _logger.warning(
                    'addCurve: Histogram does not support xlabel argument')
            if ylabel is not None:
                _logger.warning(
                    'addCurve: Histogram does not support ylabel argument')
            if yaxis is not None:
                histo.setYAxis(yaxis)
            if z is not None:
                histo.setZValue(z)
            if selectable is not None:
                _logger.warning(
                    'addCurve: Histogram does not support selectable argument')

            return

        legend = 'Unnamed curve 1.1' if legend is None else str(legend)

        # Check if curve was previously active
        wasActive = self.getActiveCurve(just_legend=True) == legend

        if replace:
            self._resetColorAndStyle()

        # Create/Update curve object
        curve = self.getCurve(legend)
        mustBeAdded = curve is None
        if curve is None:
            # No previous curve, create a default one and add it to the plot
            curve = items.Curve() if histogram is None else items.Histogram()
            curve._setLegend(legend)
            # Set default color, linestyle and symbol
            default_color, default_linestyle = self._getColorAndStyle()
            curve.setColor(default_color)
            curve.setLineStyle(default_linestyle)
            curve.setSymbol(self._defaultPlotPoints)

        # Do not emit sigActiveCurveChanged,
        # it will be sent once with _setActiveItem
        with self._muteActiveItemChangedSignal():
            # Override previous/default values with provided ones
            curve.setInfo(info)
            if color is not None:
                curve.setColor(color)
            if symbol is not None:
                curve.setSymbol(symbol)
            if linewidth is not None:
                curve.setLineWidth(linewidth)
            if linestyle is not None:
                curve.setLineStyle(linestyle)
            if xlabel is not None:
                curve._setXLabel(xlabel)
            if ylabel is not None:
                curve._setYLabel(ylabel)
            if yaxis is not None:
                curve.setYAxis(yaxis)
            if z is not None:
                curve.setZValue(z)
            if selectable is not None:
                curve._setSelectable(selectable)
            if fill is not None:
                curve.setFill(fill)

            # Set curve data
            # If errors not provided, reuse previous ones
            # TODO: Issue if size of data change but not that of errors
            if xerror is None:
                xerror = curve.getXErrorData(copy=False)
            if yerror is None:
                yerror = curve.getYErrorData(copy=False)

            # Convert x to timestamps so that the internal representation
            # remains floating points. The user is expected to set the axis'
            # tickMode to TickMode.TIME_SERIES and, if necessary, set the axis
            # to the correct time zone.
            if len(x) > 0 and isinstance(x[0], dt.datetime):
                x = [timestamp(d) for d in x]

            curve.setData(x, y, xerror, yerror, copy=copy)

        if replace:  # Then remove all other curves
            for c in self.getAllCurves(withhidden=True):
                if c is not curve:
                    self._remove(c)

        if mustBeAdded:
            self._add(curve)
        else:
            self._notifyContentChanged(curve)

        if wasActive:
            self.setActiveCurve(curve.getLegend())
        elif self.getActiveCurveSelectionMode() == "legacy":
            if self.getActiveCurve(just_legend=True) is None:
                if len(self.getAllCurves(just_legend=True,
                                     withhidden=False)) == 1:
                    if curve.isVisible():
                        self.setActiveCurve(curve.getLegend())

        if resetzoom:
            # We ask for a zoom reset in order to handle the plot scaling
            # if the user does not want that, autoscale of the different
            # axes has to be set to off.
            self.resetZoom()

        return legend

    def addHistogram(self,
                     histogram,
                     edges,
                     legend=None,
                     color=None,
                     fill=None,
                     align='center',
                     resetzoom=True,
                     copy=True):
        """Add an histogram to the graph.

        This is NOT computing the histogram, this method takes as parameter
        already computed histogram values.

        Histogram are uniquely identified by their legend.
        To add multiple histograms, call :meth:`addHistogram` multiple times
        with different legend argument.

        When histogram parameters are not provided, if an histogram with the
        same legend is displayed in the plot, its parameters are used.

        :param numpy.ndarray histogram: The values of the histogram.
        :param numpy.ndarray edges:
            The bin edges of the histogram.
            If histogram and edges have the same length, the bin edges
            are computed according to the align parameter.
        :param str legend:
            The legend to be associated to the histogram (or None)
        :param color: color to be used
        :type color: str ("#RRGGBB") or RGB unsigned byte array or
                     one of the predefined color names defined in colors.py
        :param bool fill: True to fill the curve, False otherwise (default).
        :param str align:
            In case histogram values and edges have the same length N,
            the N+1 bin edges are computed according to the alignment in:
            'center' (default), 'left', 'right'.
        :param bool resetzoom: True (the default) to reset the zoom.
        :param bool copy: True make a copy of the data (default),
                          False to use provided arrays.
        :returns: The key string identify this histogram
        """
        legend = 'Unnamed histogram' if legend is None else str(legend)

        # Create/Update histogram object
        histo = self.getHistogram(legend)
        mustBeAdded = histo is None
        if histo is None:
            # No previous histogram, create a default one and
            # add it to the plot
            histo = items.Histogram()
            histo._setLegend(legend)
            histo.setColor(self._getColorAndStyle()[0])

        # Override previous/default values with provided ones
        if color is not None:
            histo.setColor(color)
        if fill is not None:
            histo.setFill(fill)

        # Set histogram data
        histo.setData(histogram, edges, align=align, copy=copy)

        if mustBeAdded:
            self._add(histo)
        else:
            self._notifyContentChanged(histo)

        if resetzoom:
            # We ask for a zoom reset in order to handle the plot scaling
            # if the user does not want that, autoscale of the different
            # axes has to be set to off.
            self.resetZoom()

        return legend

    def addImage(self, data, legend=None, info=None,
                 replace=False,
                 z=None,
                 selectable=None, draggable=None,
                 colormap=None, pixmap=None,
                 xlabel=None, ylabel=None,
                 origin=None, scale=None,
                 resetzoom=True, copy=True):
        """Add a 2D dataset or an image to the plot.

        It displays either an array of data using a colormap or a RGB(A) image.

        Images are uniquely identified by their legend.
        To add multiple images, call :meth:`addImage` multiple times with
        different legend argument.
        To replace/update an existing image, call :meth:`addImage` with the
        existing image legend.

        When image parameters are not provided, if an image with the
        same legend is displayed in the plot, its parameters are used.

        :param numpy.ndarray data:
            (nrows, ncolumns) data or
            (nrows, ncolumns, RGBA) ubyte array
            Note: boolean values are converted to int8.
        :param str legend: The legend to be associated to the image (or None)
        :param info: User-defined information associated to the image
        :param bool replace:
            True to delete already existing images (Default: False).
        :param int z: Layer on which to draw the image (default: 0)
                      This allows to control the overlay.
        :param bool selectable: Indicate if the image can be selected.
                                (default: False)
        :param bool draggable: Indicate if the image can be moved.
                               (default: False)
        :param colormap: Colormap object to use (or None).
                         This is ignored if data is a RGB(A) image.
        :type colormap: Union[~silx.gui.colors.Colormap, dict]
        :param pixmap: Pixmap representation of the data (if any)
        :type pixmap: (nrows, ncolumns, RGBA) ubyte array or None (default)
        :param str xlabel: X axis label to show when this curve is active,
                           or None to keep default axis label.
        :param str ylabel: Y axis label to show when this curve is active,
                           or None to keep default axis label.
        :param origin: (origin X, origin Y) of the data.
                       It is possible to pass a single float if both
                       coordinates are equal.
                       Default: (0., 0.)
        :type origin: float or 2-tuple of float
        :param scale: (scale X, scale Y) of the data.
                      It is possible to pass a single float if both
                      coordinates are equal.
                      Default: (1., 1.)
        :type scale: float or 2-tuple of float
        :param bool resetzoom: True (the default) to reset the zoom.
        :param bool copy: True make a copy of the data (default),
                          False to use provided arrays.
        :returns: The key string identify this image
        """
        legend = "Unnamed Image 1.1" if legend is None else str(legend)

        # Check if image was previously active
        wasActive = self.getActiveImage(just_legend=True) == legend

        data = numpy.array(data, copy=False)
        assert data.ndim in (2, 3)

        image = self.getImage(legend)
        if image is not None and image.getData(copy=False).ndim != data.ndim:
            # Update a data image with RGBA image or the other way around:
            # Remove previous image
            # In this case, we don't retrieve defaults from the previous image
            self._remove(image)
            image = None

        mustBeAdded = image is None
        if image is None:
            # No previous image, create a default one and add it to the plot
            if data.ndim == 2:
                image = items.ImageData()
                image.setColormap(self.getDefaultColormap())
            else:
                image = items.ImageRgba()
            image._setLegend(legend)

        # Do not emit sigActiveImageChanged,
        # it will be sent once with _setActiveItem
        with self._muteActiveItemChangedSignal():
            # Override previous/default values with provided ones
            image.setInfo(info)
            if origin is not None:
                image.setOrigin(origin)
            if scale is not None:
                image.setScale(scale)
            if z is not None:
                image.setZValue(z)
            if selectable is not None:
                image._setSelectable(selectable)
            if draggable is not None:
                image._setDraggable(draggable)
            if colormap is not None and isinstance(image, items.ColormapMixIn):
                if isinstance(colormap, dict):
                    image.setColormap(Colormap._fromDict(colormap))
                else:
                    assert isinstance(colormap, Colormap)
                    image.setColormap(colormap)
            if xlabel is not None:
                image._setXLabel(xlabel)
            if ylabel is not None:
                image._setYLabel(ylabel)

            if data.ndim == 2:
                image.setData(data, alternative=pixmap, copy=copy)
            else:  # RGB(A) image
                if pixmap is not None:
                    _logger.warning(
                        'addImage: pixmap argument ignored when data is RGB(A)')
                image.setData(data, copy=copy)

        if replace:
            for img in self.getAllImages():
                if img is not image:
                    self._remove(img)

        if mustBeAdded:
            self._add(image)
        else:
            self._notifyContentChanged(image)

        if len(self.getAllImages()) == 1 or wasActive:
            self.setActiveImage(legend)

        if resetzoom:
            # We ask for a zoom reset in order to handle the plot scaling
            # if the user does not want that, autoscale of the different
            # axes has to be set to off.
            self.resetZoom()

        return legend

    def addScatter(self, x, y, value, legend=None, colormap=None,
                   info=None, symbol=None, xerror=None, yerror=None,
                   z=None, copy=True):
        """Add a (x, y, value) scatter to the graph.

        Scatters are uniquely identified by their legend.
        To add multiple scatters, call :meth:`addScatter` multiple times with
        different legend argument.
        To replace/update an existing scatter, call :meth:`addScatter` with the
        existing scatter legend.

        When scatter parameters are not provided, if a scatter with the
        same legend is displayed in the plot, its parameters are used.

        :param numpy.ndarray x: The data corresponding to the x coordinates.
        :param numpy.ndarray y: The data corresponding to the y coordinates
        :param numpy.ndarray value: The data value associated with each point
        :param str legend: The legend to be associated to the scatter (or None)
        :param ~silx.gui.colors.Colormap colormap:
            Colormap object to be used for the scatter (or None)
        :param info: User-defined information associated to the curve
        :param str symbol: Symbol to be drawn at each (x, y) position::

            - 'o' circle
            - '.' point
            - ',' pixel
            - '+' cross
            - 'x' x-cross
            - 'd' diamond
            - 's' square
            - None (the default) to use default symbol

        :param xerror: Values with the uncertainties on the x values
        :type xerror: A float, or a numpy.ndarray of float32.
                      If it is an array, it can either be a 1D array of
                      same length as the data or a 2D array with 2 rows
                      of same length as the data: row 0 for positive errors,
                      row 1 for negative errors.
        :param yerror: Values with the uncertainties on the y values
        :type yerror: A float, or a numpy.ndarray of float32. See xerror.
        :param int z: Layer on which to draw the scatter (default: 1)
                      This allows to control the overlay.

        :param bool copy: True make a copy of the data (default),
                          False to use provided arrays.
        :returns: The key string identify this scatter
        """
        legend = 'Unnamed scatter 1.1' if legend is None else str(legend)

        # Check if scatter was previously active
        wasActive = self._getActiveItem(kind='scatter',
                                        just_legend=True) == legend

        # Create/Update curve object
        scatter = self._getItem(kind='scatter', legend=legend)
        mustBeAdded = scatter is None
        if scatter is None:
            # No previous scatter, create a default one and add it to the plot
            scatter = items.Scatter()
            scatter._setLegend(legend)
            scatter.setColormap(self.getDefaultColormap())

        # Do not emit sigActiveScatterChanged,
        # it will be sent once with _setActiveItem
        with self._muteActiveItemChangedSignal():
            # Override previous/default values with provided ones
            scatter.setInfo(info)
            if symbol is not None:
                scatter.setSymbol(symbol)
            if z is not None:
                scatter.setZValue(z)
            if colormap is not None:
                if isinstance(colormap, dict):
                    scatter.setColormap(Colormap._fromDict(colormap))
                else:
                    assert isinstance(colormap, Colormap)
                    scatter.setColormap(colormap)

            # Set scatter data
            # If errors not provided, reuse previous ones
            if xerror is None:
                xerror = scatter.getXErrorData(copy=False)
                if xerror is not None and len(xerror) != len(x):
                    xerror = None
            if yerror is None:
                yerror = scatter.getYErrorData(copy=False)
                if yerror is not None and len(yerror) != len(y):
                    yerror = None

            scatter.setData(x, y, value, xerror, yerror, copy=copy)

        if mustBeAdded:
            self._add(scatter)
        else:
            self._notifyContentChanged(scatter)

        if len(self._getItems(kind="scatter")) == 1 or wasActive:
            self._setActiveItem('scatter', scatter.getLegend())

        return legend

    def addItem(self, xdata, ydata, legend=None, info=None,
                replace=False,
                shape="polygon", color='black', fill=True,
                overlay=False, z=None, linestyle="-", linewidth=1.0,
                linebgcolor=None):
        """Add an item (i.e. a shape) to the plot.

        Items are uniquely identified by their legend.
        To add multiple items, call :meth:`addItem` multiple times with
        different legend argument.
        To replace/update an existing item, call :meth:`addItem` with the
        existing item legend.

        :param numpy.ndarray xdata: The X coords of the points of the shape
        :param numpy.ndarray ydata: The Y coords of the points of the shape
        :param str legend: The legend to be associated to the item
        :param info: User-defined information associated to the item
        :param bool replace: True (default) to delete already existing images
        :param str shape: Type of item to be drawn in
                          hline, polygon (the default), rectangle, vline,
                          polylines
        :param str color: Color of the item, e.g., 'blue', 'b', '#FF0000'
                          (Default: 'black')
        :param bool fill: True (the default) to fill the shape
        :param bool overlay: True if item is an overlay (Default: False).
                             This allows for rendering optimization if this
                             item is changed often.
        :param int z: Layer on which to draw the item (default: 2)
        :param str linestyle: Style of the line.
            Only relevant for line markers where X or Y is None.
            Value in:

            - ' '  no line
            - '-'  solid line
            - '--' dashed line
            - '-.' dash-dot line
            - ':'  dotted line
        :param float linewidth: Width of the line.
            Only relevant for line markers where X or Y is None.
        :param str linebgcolor: Background color of the line, e.g., 'blue', 'b',
            '#FF0000'. It is used to draw dotted line using a second color.
        :returns: The key string identify this item
        """
        # expected to receive the same parameters as the signal

        legend = "Unnamed Item 1.1" if legend is None else str(legend)

        z = int(z) if z is not None else 2

        if replace:
            self.remove(kind='item')
        else:
            self.remove(legend, kind='item')

        item = items.Shape(shape)
        item._setLegend(legend)
        item.setInfo(info)
        item.setColor(color)
        item.setFill(fill)
        item.setOverlay(overlay)
        item.setZValue(z)
        item.setPoints(numpy.array((xdata, ydata)).T)
        item.setLineStyle(linestyle)
        item.setLineWidth(linewidth)
        item.setLineBgColor(linebgcolor)

        self._add(item)

        return legend

    def addXMarker(self, x, legend=None,
                   text=None,
                   color=None,
                   selectable=False,
                   draggable=False,
                   constraint=None):
        """Add a vertical line marker to the plot.

        Markers are uniquely identified by their legend.
        As opposed to curves, images and items, two calls to
        :meth:`addXMarker` without legend argument adds two markers with
        different identifying legends.

        :param float x: Position of the marker on the X axis in data
                        coordinates
        :param str legend: Legend associated to the marker to identify it
        :param str text: Text to display on the marker.
        :param str color: Color of the marker, e.g., 'blue', 'b', '#FF0000'
                          (Default: 'black')
        :param bool selectable: Indicate if the marker can be selected.
                                (default: False)
        :param bool draggable: Indicate if the marker can be moved.
                               (default: False)
        :param constraint: A function filtering marker displacement by
                           dragging operations or None for no filter.
                           This function is called each time a marker is
                           moved.
                           This parameter is only used if draggable is True.
        :type constraint: None or a callable that takes the coordinates of
                          the current cursor position in the plot as input
                          and that returns the filtered coordinates.
        :return: The key string identify this marker
        """
        return self._addMarker(x=x, y=None, legend=legend,
                               text=text, color=color,
                               selectable=selectable, draggable=draggable,
                               symbol=None, constraint=constraint)

    def addYMarker(self, y,
                   legend=None,
                   text=None,
                   color=None,
                   selectable=False,
                   draggable=False,
                   constraint=None):
        """Add a horizontal line marker to the plot.

        Markers are uniquely identified by their legend.
        As opposed to curves, images and items, two calls to
        :meth:`addYMarker` without legend argument adds two markers with
        different identifying legends.

        :param float y: Position of the marker on the Y axis in data
                        coordinates
        :param str legend: Legend associated to the marker to identify it
        :param str text: Text to display next to the marker.
        :param str color: Color of the marker, e.g., 'blue', 'b', '#FF0000'
                          (Default: 'black')
        :param bool selectable: Indicate if the marker can be selected.
                                (default: False)
        :param bool draggable: Indicate if the marker can be moved.
                               (default: False)
        :param constraint: A function filtering marker displacement by
                           dragging operations or None for no filter.
                           This function is called each time a marker is
                           moved.
                           This parameter is only used if draggable is True.
        :type constraint: None or a callable that takes the coordinates of
                          the current cursor position in the plot as input
                          and that returns the filtered coordinates.
        :return: The key string identify this marker
        """
        return self._addMarker(x=None, y=y, legend=legend,
                               text=text, color=color,
                               selectable=selectable, draggable=draggable,
                               symbol=None, constraint=constraint)

    def addMarker(self, x, y, legend=None,
                  text=None,
                  color=None,
                  selectable=False,
                  draggable=False,
                  symbol='+',
                  constraint=None):
        """Add a point marker to the plot.

        Markers are uniquely identified by their legend.
        As opposed to curves, images and items, two calls to
        :meth:`addMarker` without legend argument adds two markers with
        different identifying legends.

        :param float x: Position of the marker on the X axis in data
                        coordinates
        :param float y: Position of the marker on the Y axis in data
                        coordinates
        :param str legend: Legend associated to the marker to identify it
        :param str text: Text to display next to the marker
        :param str color: Color of the marker, e.g., 'blue', 'b', '#FF0000'
                          (Default: 'black')
        :param bool selectable: Indicate if the marker can be selected.
                                (default: False)
        :param bool draggable: Indicate if the marker can be moved.
                               (default: False)
        :param str symbol: Symbol representing the marker in::

            - 'o' circle
            - '.' point
            - ',' pixel
            - '+' cross (the default)
            - 'x' x-cross
            - 'd' diamond
            - 's' square

        :param constraint: A function filtering marker displacement by
                           dragging operations or None for no filter.
                           This function is called each time a marker is
                           moved.
                           This parameter is only used if draggable is True.
        :type constraint: None or a callable that takes the coordinates of
                          the current cursor position in the plot as input
                          and that returns the filtered coordinates.
        :return: The key string identify this marker
        """
        if x is None:
            xmin, xmax = self._xAxis.getLimits()
            x = 0.5 * (xmax + xmin)

        if y is None:
            ymin, ymax = self._yAxis.getLimits()
            y = 0.5 * (ymax + ymin)

        return self._addMarker(x=x, y=y, legend=legend,
                               text=text, color=color,
                               selectable=selectable, draggable=draggable,
                               symbol=symbol, constraint=constraint)

    def _addMarker(self, x, y, legend,
                   text, color,
                   selectable, draggable,
                   symbol, constraint):
        """Common method for adding point, vline and hline marker.

        See :meth:`addMarker` for argument documentation.
        """
        assert (x, y) != (None, None)

        if legend is None:  # Find an unused legend
            markerLegends = self._getAllMarkers(just_legend=True)
            for index in itertools.count():
                legend = "Unnamed Marker %d" % index
                if legend not in markerLegends:
                    break  # Keep this legend
        legend = str(legend)

        if x is None:
            markerClass = items.YMarker
        elif y is None:
            markerClass = items.XMarker
        else:
            markerClass = items.Marker

        # Create/Update marker object
        marker = self._getMarker(legend)
        if marker is not None and not isinstance(marker, markerClass):
            _logger.warning('Adding marker with same legend'
                            ' but different type replaces it')
            self._remove(marker)
            marker = None

        mustBeAdded = marker is None
        if marker is None:
            # No previous marker, create one
            marker = markerClass()
            marker._setLegend(legend)

        if text is not None:
            marker.setText(text)
        if color is not None:
            marker.setColor(color)
        if selectable is not None:
            marker._setSelectable(selectable)
        if draggable is not None:
            marker._setDraggable(draggable)
        if symbol is not None:
            marker.setSymbol(symbol)

        # TODO to improve, but this ensure constraint is applied
        marker.setPosition(x, y)
        if constraint is not None:
            marker._setConstraint(constraint)
        marker.setPosition(x, y)

        if mustBeAdded:
            self._add(marker)
        else:
            self._notifyContentChanged(marker)

        return legend

    # Hide

    def isCurveHidden(self, legend):
        """Returns True if the curve associated to legend is hidden, else False

        :param str legend: The legend key identifying the curve
        :return: True if the associated curve is hidden, False otherwise
        """
        curve = self._getItem('curve', legend)
        return curve is not None and not curve.isVisible()

    def hideCurve(self, legend, flag=True):
        """Show/Hide the curve associated to legend.

        Even when hidden, the curve is kept in the list of curves.

        :param str legend: The legend associated to the curve to be hidden
        :param bool flag: True (default) to hide the curve, False to show it
        """
        curve = self._getItem('curve', legend)
        if curve is None:
            _logger.warning('Curve not in plot: %s', legend)
            return

        isVisible = not flag
        if isVisible != curve.isVisible():
            curve.setVisible(isVisible)

    # Remove

    ITEM_KINDS = 'curve', 'image', 'scatter', 'item', 'marker', 'histogram'
    """List of supported kind of items in the plot."""

    _ACTIVE_ITEM_KINDS = 'curve', 'scatter', 'image'
    """List of item's kind which have a active item."""

    def remove(self, legend=None, kind=ITEM_KINDS):
        """Remove one or all element(s) of the given legend and kind.

        Examples:

        - ``remove()`` clears the plot
        - ``remove(kind='curve')`` removes all curves from the plot
        - ``remove('myCurve', kind='curve')`` removes the curve with
          legend 'myCurve' from the plot.
        - ``remove('myImage, kind='image')`` removes the image with
          legend 'myImage' from the plot.
        - ``remove('myImage')`` removes elements (for instance curve, image,
          item and marker) with legend 'myImage'.

        :param str legend: The legend associated to the element to remove,
                           or None to remove
        :param kind: The kind of elements to remove from the plot.
                     See :attr:`ITEM_KINDS`.
                     By default, it removes all kind of elements.
        :type kind: str or tuple of str to specify multiple kinds.
        """
        if kind is 'all':  # Replace all by tuple of all kinds
            kind = self.ITEM_KINDS

        if kind in self.ITEM_KINDS:  # Kind is a str, make it a tuple
            kind = (kind,)

        for aKind in kind:
            assert aKind in self.ITEM_KINDS

        if legend is None:  # This is a clear
            # Clear each given kind
            for aKind in kind:
                for legend in self._getItems(
                        kind=aKind, just_legend=True, withhidden=True):
                    self.remove(legend=legend, kind=aKind)

        else:  # This is removing a single element
            # Remove each given kind
            for aKind in kind:
                item = self._getItem(aKind, legend)
                if item is not None:
                    self._remove(item)

    def removeCurve(self, legend):
        """Remove the curve associated to legend from the graph.

        :param str legend: The legend associated to the curve to be deleted
        """
        if legend is None:
            return
        self.remove(legend, kind='curve')

    def removeImage(self, legend):
        """Remove the image associated to legend from the graph.

        :param str legend: The legend associated to the image to be deleted
        """
        if legend is None:
            return
        self.remove(legend, kind='image')

    def removeItem(self, legend):
        """Remove the item associated to legend from the graph.

        :param str legend: The legend associated to the item to be deleted
        """
        if legend is None:
            return
        self.remove(legend, kind='item')

    def removeMarker(self, legend):
        """Remove the marker associated to legend from the graph.

        :param str legend: The legend associated to the marker to be deleted
        """
        if legend is None:
            return
        self.remove(legend, kind='marker')

    # Clear

    def clear(self):
        """Remove everything from the plot."""
        self.remove()

    def clearCurves(self):
        """Remove all the curves from the plot."""
        self.remove(kind='curve')

    def clearImages(self):
        """Remove all the images from the plot."""
        self.remove(kind='image')

    def clearItems(self):
        """Remove all the items from the plot. """
        self.remove(kind='item')

    def clearMarkers(self):
        """Remove all the markers from the plot."""
        self.remove(kind='marker')

    # Interaction

    def getGraphCursor(self):
        """Returns the state of the crosshair cursor.

        See :meth:`setGraphCursor`.

        :return: None if the crosshair cursor is not active,
                 else a tuple (color, linewidth, linestyle).
        """
        return self._cursorConfiguration

    def setGraphCursor(self, flag=False, color='black',
                       linewidth=1, linestyle='-'):
        """Toggle the display of a crosshair cursor and set its attributes.

        :param bool flag: Toggle the display of a crosshair cursor.
                          The crosshair cursor is hidden by default.
        :param color: The color to use for the crosshair.
        :type color: A string (either a predefined color name in colors.py
                    or "#RRGGBB")) or a 4 columns unsigned byte array
                    (Default: black).
        :param int linewidth: The width of the lines of the crosshair
                    (Default: 1).
        :param str linestyle: Type of line::

                - ' ' no line
                - '-' solid line (the default)
                - '--' dashed line
                - '-.' dash-dot line
                - ':' dotted line
        """
        if flag:
            self._cursorConfiguration = color, linewidth, linestyle
        else:
            self._cursorConfiguration = None

        self._backend.setGraphCursor(flag=flag, color=color,
                                     linewidth=linewidth, linestyle=linestyle)
        self._setDirtyPlot()
        self.notify('setGraphCursor',
                    state=self._cursorConfiguration is not None)

    def pan(self, direction, factor=0.1):
        """Pan the graph in the given direction by the given factor.

        Warning: Pan of right Y axis not implemented!

        :param str direction: One of 'up', 'down', 'left', 'right'.
        :param float factor: Proportion of the range used to pan the graph.
                             Must be strictly positive.
        """
        assert direction in ('up', 'down', 'left', 'right')
        assert factor > 0.

        if direction in ('left', 'right'):
            xFactor = factor if direction == 'right' else - factor
            xMin, xMax = self._xAxis.getLimits()

            xMin, xMax = _utils.applyPan(xMin, xMax, xFactor,
                                         self._xAxis.getScale() == self._xAxis.LOGARITHMIC)
            self._xAxis.setLimits(xMin, xMax)

        else:  # direction in ('up', 'down')
            sign = -1. if self._yAxis.isInverted() else 1.
            yFactor = sign * (factor if direction == 'up' else -factor)
            yMin, yMax = self._yAxis.getLimits()
            yIsLog = self._yAxis.getScale() == self._yAxis.LOGARITHMIC

            yMin, yMax = _utils.applyPan(yMin, yMax, yFactor, yIsLog)
            self._yAxis.setLimits(yMin, yMax)

            y2Min, y2Max = self._yRightAxis.getLimits()

            y2Min, y2Max = _utils.applyPan(y2Min, y2Max, yFactor, yIsLog)
            self._yRightAxis.setLimits(y2Min, y2Max)

    # Active Curve/Image

    def isActiveCurveHandling(self):
        """Returns True if active curve selection is enabled.

        :rtype: bool
        """
        return self.getActiveCurveSelectionMode() != 'none'

    def setActiveCurveHandling(self, flag=True):
        """Enable/Disable active curve selection.

        :param bool flag: True to enable 'atmostone' active curve selection,
            False to disable active curve selection.
        """
        self.setActiveCurveSelectionMode('atmostone' if flag else 'none')

    def getActiveCurveStyle(self):
        """Returns the current style applied to active curve

        :rtype: CurveStyle
        """
        return self._activeCurveStyle

    def setActiveCurveStyle(self,
                            color=None,
                            linewidth=None,
                            linestyle=None,
                            symbol=None,
                            symbolsize=None):
        """Set the style of active curve

        :param color: Color
        :param Union[str,None] linestyle: Style of the line
        :param Union[float,None] linewidth: Width of the line
        :param Union[str,None] symbol: Symbol of the markers
        :param Union[float,None] symbolsize: Size of the symbols
        """
        self._activeCurveStyle = CurveStyle(color=color,
                                            linewidth=linewidth,
                                            linestyle=linestyle,
                                            symbol=symbol,
                                            symbolsize=symbolsize)
        curve = self.getActiveCurve()
        if curve is not None:
            curve.setHighlightedStyle(self.getActiveCurveStyle())

    @deprecated(replacement="getActiveCurveStyle", since_version="0.9")
    def getActiveCurveColor(self):
        """Get the color used to display the currently active curve.

        See :meth:`setActiveCurveColor`.
        """
        return self._activeCurveStyle.getColor()

    @deprecated(replacement="setActiveCurveStyle", since_version="0.9")
    def setActiveCurveColor(self, color="#000000"):
        """Set the color to use to display the currently active curve.

        :param str color: Color of the active curve,
                          e.g., 'blue', 'b', '#FF0000' (Default: 'black')
        """
        if color is None:
            color = "black"
        if color in self.colorDict:
            color = self.colorDict[color]
        self.setActiveCurveStyle(color=color)

    def getActiveCurve(self, just_legend=False):
        """Return the currently active curve.

        It returns None in case of not having an active curve.

        :param bool just_legend: True to get the legend of the curve,
                                 False (the default) to get the curve data
                                 and info.
        :return: Active curve's legend or corresponding
                 :class:`.items.Curve`
        :rtype: str or :class:`.items.Curve` or None
        """
        if not self.isActiveCurveHandling():
            return None

        return self._getActiveItem(kind='curve', just_legend=just_legend)

    def setActiveCurve(self, legend):
        """Make the curve associated to legend the active curve.

        :param legend: The legend associated to the curve
                       or None to have no active curve.
        :type legend: str or None
        """
        if not self.isActiveCurveHandling():
            return
        if legend is None and self.getActiveCurveSelectionMode() == "legacy":
            _logger.info(
                'setActiveCurve(None) ignored due to active curve selection mode')
            return

        return self._setActiveItem(kind='curve', legend=legend)

    def setActiveCurveSelectionMode(self, mode):
        """Sets the current selection mode.

        :param str mode: The active curve selection mode to use.
            It can be: 'legacy', 'atmostone' or 'none'.
        """
        assert mode in ('legacy', 'atmostone', 'none')

        if mode != self._activeCurveSelectionMode:
            self._activeCurveSelectionMode = mode
            if mode == 'none':  # reset active curve
                self._setActiveItem(kind='curve', legend=None)

            elif mode == 'legacy' and self.getActiveCurve() is None:
                # Select an active curve
                curves = self.getAllCurves(just_legend=False,
                                           withhidden=False)
                if len(curves) == 1:
                    if curves[0].isVisible():
                        self.setActiveCurve(curves[0].getLegend())

    def getActiveCurveSelectionMode(self):
        """Returns the current selection mode.

        It can be "atmostone", "legacy" or "none".

        :rtype: str
        """
        return self._activeCurveSelectionMode

    def getActiveImage(self, just_legend=False):
        """Returns the currently active image.

        It returns None in case of not having an active image.

        :param bool just_legend: True to get the legend of the image,
                                 False (the default) to get the image data
                                 and info.
        :return: Active image's legend or corresponding image object
        :rtype: str, :class:`.items.ImageData`, :class:`.items.ImageRgba`
                or None
        """
        return self._getActiveItem(kind='image', just_legend=just_legend)

    def setActiveImage(self, legend):
        """Make the image associated to legend the active image.

        :param str legend: The legend associated to the image
                           or None to have no active image.
        """
        return self._setActiveItem(kind='image', legend=legend)

    def _getActiveItem(self, kind, just_legend=False):
        """Return the currently active item of that kind if any

        :param str kind: Type of item: 'curve', 'scatter' or 'image'
        :param bool just_legend: True to get the legend,
                                 False (default) to get the item
        :return: legend or item or None if no active item
        """
        assert kind in self._ACTIVE_ITEM_KINDS

        if self._activeLegend[kind] is None:
            return None

        if (self._activeLegend[kind], kind) not in self._content:
            self._activeLegend[kind] = None
            return None

        if just_legend:
            return self._activeLegend[kind]
        else:
            return self._getItem(kind, self._activeLegend[kind])

    def _setActiveItem(self, kind, legend):
        """Make the curve associated to legend the active curve.

        :param str kind: Type of item: 'curve' or 'image'
        :param legend: The legend associated to the curve
                       or None to have no active curve.
        :type legend: str or None
        """
        assert kind in self._ACTIVE_ITEM_KINDS

        xLabel = None
        yLabel = None
        yRightLabel = None

        oldActiveItem = self._getActiveItem(kind=kind)

        if oldActiveItem is not None:  # Stop listening previous active image
            oldActiveItem.sigItemChanged.disconnect(self._activeItemChanged)

        # Curve specific: Reset highlight of previous active curve
        if kind == 'curve' and oldActiveItem is not None:
            oldActiveItem.setHighlighted(False)

        if legend is None:
            self._activeLegend[kind] = None
        else:
            legend = str(legend)
            item = self._getItem(kind, legend)
            if item is None:
                _logger.warning("This %s does not exist: %s", kind, legend)
                self._activeLegend[kind] = None
            else:
                self._activeLegend[kind] = legend

                # Curve specific: handle highlight
                if kind == 'curve':
                    item.setHighlightedStyle(self.getActiveCurveStyle())
                    item.setHighlighted(True)

                if isinstance(item, items.LabelsMixIn):
                    if item.getXLabel() is not None:
                        xLabel = item.getXLabel()
                    if item.getYLabel() is not None:
                        if (isinstance(item, items.YAxisMixIn) and
                                item.getYAxis() == 'right'):
                            yRightLabel = item.getYLabel()
                        else:
                            yLabel = item.getYLabel()

                # Start listening new active item
                item.sigItemChanged.connect(self._activeItemChanged)

        # Store current labels and update plot
        self._xAxis._setCurrentLabel(xLabel)
        self._yAxis._setCurrentLabel(yLabel)
        self._yRightAxis._setCurrentLabel(yRightLabel)

        self._setDirtyPlot()

        activeLegend = self._activeLegend[kind]
        if oldActiveItem is not None or activeLegend is not None:
            if oldActiveItem is None:
                oldActiveLegend = None
            else:
                oldActiveLegend = oldActiveItem.getLegend()
            self.notify(
                'active' + kind[0].upper() + kind[1:] + 'Changed',
                updated=oldActiveLegend != activeLegend,
                previous=oldActiveLegend,
                legend=activeLegend)

        return activeLegend

    def _activeItemChanged(self, type_):
        """Listen for active item changed signal and broadcast signal

        :param item.ItemChangedType type_: The type of item change
        """
        if not self.__muteActiveItemChanged:
            item = self.sender()
            if item is not None:
                legend, kind = self._itemKey(item)
                self.notify(
                    'active' + kind[0].upper() + kind[1:] + 'Changed',
                    updated=False,
                    previous=legend,
                    legend=legend)

    # Getters

    def getItems(self):
        """Returns the list of items in the plot

        :rtype: List[silx.gui.plot.items.Item]
        """
        return tuple(self._content.values())

    def getAllCurves(self, just_legend=False, withhidden=False):
        """Returns all curves legend or info and data.

        It returns an empty list in case of not having any curve.

        If just_legend is False, it returns a list of :class:`items.Curve`
        objects describing the curves.
        If just_legend is True, it returns a list of curves' legend.

        :param bool just_legend: True to get the legend of the curves,
                                 False (the default) to get the curves' data
                                 and info.
        :param bool withhidden: False (default) to skip hidden curves.
        :return: list of curves' legend or :class:`.items.Curve`
        :rtype: list of str or list of :class:`.items.Curve`
        """
        return self._getItems(kind='curve',
                              just_legend=just_legend,
                              withhidden=withhidden)

    def getCurve(self, legend=None):
        """Get the object describing a specific curve.

        It returns None in case no matching curve is found.

        :param str legend:
            The legend identifying the curve.
            If not provided or None (the default), the active curve is returned
            or if there is no active curve, the latest updated curve that is
            not hidden is returned if there are curves in the plot.
        :return: None or :class:`.items.Curve` object
        """
        return self._getItem(kind='curve', legend=legend)

    def getAllImages(self, just_legend=False):
        """Returns all images legend or objects.

        It returns an empty list in case of not having any image.

        If just_legend is False, it returns a list of :class:`items.ImageBase`
        objects describing the images.
        If just_legend is True, it returns a list of legends.

        :param bool just_legend: True to get the legend of the images,
                                 False (the default) to get the images'
                                 object.
        :return: list of images' legend or :class:`.items.ImageBase`
        :rtype: list of str or list of :class:`.items.ImageBase`
        """
        return self._getItems(kind='image',
                              just_legend=just_legend,
                              withhidden=True)

    def getImage(self, legend=None):
        """Get the object describing a specific image.

        It returns None in case no matching image is found.

        :param str legend:
            The legend identifying the image.
            If not provided or None (the default), the active image is returned
            or if there is no active image, the latest updated image
            is returned if there are images in the plot.
        :return: None or :class:`.items.ImageBase` object
        """
        return self._getItem(kind='image', legend=legend)

    def getScatter(self, legend=None):
        """Get the object describing a specific scatter.

        It returns None in case no matching scatter is found.

        :param str legend:
            The legend identifying the scatter.
            If not provided or None (the default), the active scatter is
            returned or if there is no active scatter, the latest updated
            scatter is returned if there are scatters in the plot.
        :return: None or :class:`.items.Scatter` object
        """
        return self._getItem(kind='scatter', legend=legend)

    def getHistogram(self, legend=None):
        """Get the object describing a specific histogram.

        It returns None in case no matching histogram is found.

        :param str legend:
            The legend identifying the histogram.
            If not provided or None (the default), the latest updated scatter
            is returned if there are histograms in the plot.
        :return: None or :class:`.items.Histogram` object
        """
        return self._getItem(kind='histogram', legend=legend)

    def _getItems(self, kind=ITEM_KINDS, just_legend=False, withhidden=False):
        """Retrieve all items of a kind in the plot

        :param kind: The kind of elements to retrieve from the plot.
                     See :attr:`ITEM_KINDS`.
                     By default, it removes all kind of elements.
        :type kind: str or tuple of str to specify multiple kinds.
        :param str kind: Type of item: 'curve' or 'image'
        :param bool just_legend: True to get the legend of the curves,
                                 False (the default) to get the curves' data
                                 and info.
        :param bool withhidden: False (default) to skip hidden curves.
        :return: list of legends or item objects
        """
        if kind is 'all':  # Replace all by tuple of all kinds
            kind = self.ITEM_KINDS

        if kind in self.ITEM_KINDS:  # Kind is a str, make it a tuple
            kind = (kind,)

        for aKind in kind:
            assert aKind in self.ITEM_KINDS

        output = []
        for (legend, type_), item in self._content.items():
            if type_ in kind and (withhidden or item.isVisible()):
                output.append(legend if just_legend else item)
        return output

    def _getItem(self, kind, legend=None):
        """Get an item from the plot: either an image or a curve.

        Returns None if no match found.

        :param str kind: Type of item to retrieve,
                         see :attr:`ITEM_KINDS`.
        :param str legend: Legend of the item or
                           None to get active or last item
        :return: Object describing the item or None
        """
        assert kind in self.ITEM_KINDS

        if legend is not None:
            return self._content.get((legend, kind), None)
        else:
            if kind in self._ACTIVE_ITEM_KINDS:
                item = self._getActiveItem(kind=kind)
                if item is not None:  # Return active item if available
                    return item
            # Return last visible item if any
            allItems = self._getItems(
                kind=kind, just_legend=False, withhidden=False)
            return allItems[-1] if allItems else None

    # Limits

    def _notifyLimitsChanged(self, emitSignal=True):
        """Send an event when plot area limits are changed."""
        xRange = self._xAxis.getLimits()
        yRange = self._yAxis.getLimits()
        y2Range = self._yRightAxis.getLimits()
        if emitSignal:
            axes = self.getXAxis(), self.getYAxis(), self.getYAxis(axis="right")
            ranges = xRange, yRange, y2Range
            for axis, limits in zip(axes, ranges):
                axis.sigLimitsChanged.emit(*limits)
        event = PlotEvents.prepareLimitsChangedSignal(
            id(self.getWidgetHandle()), xRange, yRange, y2Range)
        self.notify(**event)

    def getLimitsHistory(self):
        """Returns the object handling the history of limits of the plot"""
        return self._limitsHistory

    def getGraphXLimits(self):
        """Get the graph X (bottom) limits.

        :return: Minimum and maximum values of the X axis
        """
        return self._backend.getGraphXLimits()

    def setGraphXLimits(self, xmin, xmax):
        """Set the graph X (bottom) limits.

        :param float xmin: minimum bottom axis value
        :param float xmax: maximum bottom axis value
        """
        self._xAxis.setLimits(xmin, xmax)

    def getGraphYLimits(self, axis='left'):
        """Get the graph Y limits.

        :param str axis: The axis for which to get the limits:
                         Either 'left' or 'right'
        :return: Minimum and maximum values of the X axis
        """
        assert axis in ('left', 'right')
        yAxis = self._yAxis if axis == 'left' else self._yRightAxis
        return yAxis.getLimits()

    def setGraphYLimits(self, ymin, ymax, axis='left'):
        """Set the graph Y limits.

        :param float ymin: minimum bottom axis value
        :param float ymax: maximum bottom axis value
        :param str axis: The axis for which to get the limits:
                         Either 'left' or 'right'
        """
        assert axis in ('left', 'right')
        yAxis = self._yAxis if axis == 'left' else self._yRightAxis
        return yAxis.setLimits(ymin, ymax)

    def setLimits(self, xmin, xmax, ymin, ymax, y2min=None, y2max=None):
        """Set the limits of the X and Y axes at once.

        If y2min or y2max is None, the right Y axis limits are not updated.

        :param float xmin: minimum bottom axis value
        :param float xmax: maximum bottom axis value
        :param float ymin: minimum left axis value
        :param float ymax: maximum left axis value
        :param float y2min: minimum right axis value or None (the default)
        :param float y2max: maximum right axis value or None (the default)
        """
        # Deal with incorrect values
        axis = self.getXAxis()
        xmin, xmax = axis._checkLimits(xmin, xmax)
        axis = self.getYAxis()
        ymin, ymax = axis._checkLimits(ymin, ymax)

        if y2min is None or y2max is None:
            # if one limit is None, both are ignored
            y2min, y2max = None, None
        else:
            axis = self.getYAxis(axis="right")
            y2min, y2max = axis._checkLimits(y2min, y2max)

        if self._viewConstrains:
            view = self._viewConstrains.normalize(xmin, xmax, ymin, ymax)
            xmin, xmax, ymin, ymax = view

        self._backend.setLimits(xmin, xmax, ymin, ymax, y2min, y2max)
        self._setDirtyPlot()
        self._notifyLimitsChanged()

    def _getViewConstraints(self):
        """Return the plot object managing constaints on the plot view.

        :rtype: ViewConstraints
        """
        if self._viewConstrains is None:
            self._viewConstrains = ViewConstraints()
        return self._viewConstrains

    # Title and labels

    def getGraphTitle(self):
        """Return the plot main title as a str."""
        return self._graphTitle

    def setGraphTitle(self, title=""):
        """Set the plot main title.

        :param str title: Main title of the plot (default: '')
        """
        self._graphTitle = str(title)
        self._backend.setGraphTitle(title)
        self._setDirtyPlot()

    def getGraphXLabel(self):
        """Return the current X axis label as a str."""
        return self._xAxis.getLabel()

    def setGraphXLabel(self, label="X"):
        """Set the plot X axis label.

        The provided label can be temporarily replaced by the X label of the
        active curve if any.

        :param str label: The X axis label (default: 'X')
        """
        self._xAxis.setLabel(label)

    def getGraphYLabel(self, axis='left'):
        """Return the current Y axis label as a str.

        :param str axis: The Y axis for which to get the label (left or right)
        """
        assert axis in ('left', 'right')
        yAxis = self._yAxis if axis == 'left' else self._yRightAxis
        return yAxis.getLabel()

    def setGraphYLabel(self, label="Y", axis='left'):
        """Set the plot Y axis label.

        The provided label can be temporarily replaced by the Y label of the
        active curve if any.

        :param str label: The Y axis label (default: 'Y')
        :param str axis: The Y axis for which to set the label (left or right)
        """
        assert axis in ('left', 'right')
        yAxis = self._yAxis if axis == 'left' else self._yRightAxis
        return yAxis.setLabel(label)

    # Axes

    def getXAxis(self):
        """Returns the X axis

        .. versionadded:: 0.6

        :rtype: :class:`.items.Axis`
        """
        return self._xAxis

    def getYAxis(self, axis="left"):
        """Returns an Y axis

        .. versionadded:: 0.6

        :param str axis: The Y axis to return
                         ('left' or 'right').
        :rtype: :class:`.items.Axis`
        """
        assert(axis in ["left", "right"])
        return self._yAxis if axis == "left" else self._yRightAxis

    def setAxesDisplayed(self, displayed):
        """Display or not the axes.

        :param bool displayed: If `True` axes are displayed. If `False` axes
            are not anymore visible and the margin used for them is removed.
        """
        self._backend.setAxesDisplayed(displayed)
        self._setDirtyPlot()
        self._sigAxesVisibilityChanged.emit(displayed)

    def _isAxesDisplayed(self):
        return self._backend.isAxesDisplayed()

    def setYAxisInverted(self, flag=True):
        """Set the Y axis orientation.

        :param bool flag: True for Y axis going from top to bottom,
                          False for Y axis going from bottom to top
        """
        self._yAxis.setInverted(flag)

    def isYAxisInverted(self):
        """Return True if Y axis goes from top to bottom, False otherwise."""
        return self._yAxis.isInverted()

    def isXAxisLogarithmic(self):
        """Return True if X axis scale is logarithmic, False if linear."""
        return self._xAxis._isLogarithmic()

    def setXAxisLogarithmic(self, flag):
        """Set the bottom X axis scale (either linear or logarithmic).

        :param bool flag: True to use a logarithmic scale, False for linear.
        """
        self._xAxis._setLogarithmic(flag)

    def isYAxisLogarithmic(self):
        """Return True if Y axis scale is logarithmic, False if linear."""
        return self._yAxis._isLogarithmic()

    def setYAxisLogarithmic(self, flag):
        """Set the Y axes scale (either linear or logarithmic).

        :param bool flag: True to use a logarithmic scale, False for linear.
        """
        self._yAxis._setLogarithmic(flag)

    def isXAxisAutoScale(self):
        """Return True if X axis is automatically adjusting its limits."""
        return self._xAxis.isAutoScale()

    def setXAxisAutoScale(self, flag=True):
        """Set the X axis limits adjusting behavior of :meth:`resetZoom`.

        :param bool flag: True to resize limits automatically,
                          False to disable it.
        """
        self._xAxis.setAutoScale(flag)

    def isYAxisAutoScale(self):
        """Return True if Y axes are automatically adjusting its limits."""
        return self._yAxis.isAutoScale()

    def setYAxisAutoScale(self, flag=True):
        """Set the Y axis limits adjusting behavior of :meth:`resetZoom`.

        :param bool flag: True to resize limits automatically,
                          False to disable it.
        """
        self._yAxis.setAutoScale(flag)

    def isKeepDataAspectRatio(self):
        """Returns whether the plot is keeping data aspect ratio or not."""
        return self._backend.isKeepDataAspectRatio()

    def setKeepDataAspectRatio(self, flag=True):
        """Set whether the plot keeps data aspect ratio or not.

        :param bool flag: True to respect data aspect ratio
        """
        flag = bool(flag)
        if flag == self.isKeepDataAspectRatio():
            return
        self._backend.setKeepDataAspectRatio(flag=flag)
        self._setDirtyPlot()
        self._forceResetZoom()
        self.notify('setKeepDataAspectRatio', state=flag)

    def getGraphGrid(self):
        """Return the current grid mode, either None, 'major' or 'both'.

        See :meth:`setGraphGrid`.
        """
        return self._grid

    def setGraphGrid(self, which=True):
        """Set the type of grid to display.

        :param which: None or False to disable the grid,
                      'major' or True for grid on major ticks (the default),
                      'both' for grid on both major and minor ticks.
        :type which: str of bool
        """
        assert which in (None, True, False, 'both', 'major')
        if not which:
            which = None
        elif which is True:
            which = 'major'
        self._grid = which
        self._backend.setGraphGrid(which)
        self._setDirtyPlot()
        self.notify('setGraphGrid', which=str(which))

    # Defaults

    def isDefaultPlotPoints(self):
        """Return True if the default Curve symbol is set and False if not."""
        return self._defaultPlotPoints == silx.config.DEFAULT_PLOT_SYMBOL

    def setDefaultPlotPoints(self, flag):
        """Set the default symbol of all curves.

        When called, this reset the symbol of all existing curves.

        :param bool flag: True to use 'o' as the default curve symbol,
                          False to use no symbol.
        """
        self._defaultPlotPoints = silx.config.DEFAULT_PLOT_SYMBOL if flag else ''

        # Reset symbol of all curves
        curves = self.getAllCurves(just_legend=False, withhidden=True)

        if curves:
            for curve in curves:
                curve.setSymbol(self._defaultPlotPoints)

    def isDefaultPlotLines(self):
        """Return True for line as default line style, False for no line."""
        return self._plotLines

    def setDefaultPlotLines(self, flag):
        """Toggle the use of lines as the default curve line style.

        :param bool flag: True to use a line as the default line style,
                          False to use no line as the default line style.
        """
        self._plotLines = bool(flag)

        linestyle = '-' if self._plotLines else ' '

        # Reset linestyle of all curves
        curves = self.getAllCurves(withhidden=True)

        if curves:
            for curve in curves:
                curve.setLineStyle(linestyle)

    def getDefaultColormap(self):
        """Return the default colormap used by :meth:`addImage`.

        :rtype: ~silx.gui.colors.Colormap
        """
        return self._defaultColormap

    def setDefaultColormap(self, colormap=None):
        """Set the default colormap used by :meth:`addImage`.

        Setting the default colormap do not change any currently displayed
        image.
        It only affects future calls to :meth:`addImage` without the colormap
        parameter.

        :param ~silx.gui.colors.Colormap colormap:
            The description of the default colormap, or
            None to set the colormap to a linear
            autoscale gray colormap.
        """
        if colormap is None:
            colormap = Colormap(name=silx.config.DEFAULT_COLORMAP_NAME,
                                normalization='linear',
                                vmin=None,
                                vmax=None)
        if isinstance(colormap, dict):
            self._defaultColormap = Colormap._fromDict(colormap)
        else:
            assert isinstance(colormap, Colormap)
            self._defaultColormap = colormap
        self.notify('defaultColormapChanged')

    @staticmethod
    def getSupportedColormaps():
        """Get the supported colormap names as a tuple of str.

        The list contains at least:
        ('gray', 'reversed gray', 'temperature', 'red', 'green', 'blue',
        'magma', 'inferno', 'plasma', 'viridis')
        """
        return Colormap.getSupportedColormaps()

    def _resetColorAndStyle(self):
        self._colorIndex = 0
        self._styleIndex = 0

    def _getColorAndStyle(self):
        color = self.colorList[self._colorIndex]
        style = self._styleList[self._styleIndex]

        # Loop over color and then styles
        self._colorIndex += 1
        if self._colorIndex >= len(self.colorList):
            self._colorIndex = 0
            self._styleIndex = (self._styleIndex + 1) % len(self._styleList)

        # If color is the one of active curve, take the next one
        if colors.rgba(color) == self.getActiveCurveStyle().getColor():
            color, style = self._getColorAndStyle()

        if not self._plotLines:
            style = ' '

        return color, style

    # Misc.

    def getWidgetHandle(self):
        """Return the widget the plot is displayed in.

        This widget is owned by the backend.
        """
        return self._backend.getWidgetHandle()

    def notify(self, event, **kwargs):
        """Send an event to the listeners and send signals.

        Event are passed to the registered callback as a dict with an 'event'
        key for backward compatibility with PyMca.

        :param str event: The type of event
        :param kwargs: The information of the event.
        """
        eventDict = kwargs.copy()
        eventDict['event'] = event
        self.sigPlotSignal.emit(eventDict)

        if event == 'setKeepDataAspectRatio':
            self.sigSetKeepDataAspectRatio.emit(kwargs['state'])
        elif event == 'setGraphGrid':
            self.sigSetGraphGrid.emit(kwargs['which'])
        elif event == 'setGraphCursor':
            self.sigSetGraphCursor.emit(kwargs['state'])
        elif event == 'contentChanged':
            self.sigContentChanged.emit(
                kwargs['action'], kwargs['kind'], kwargs['legend'])
        elif event == 'activeCurveChanged':
            self.sigActiveCurveChanged.emit(
                kwargs['previous'], kwargs['legend'])
        elif event == 'activeImageChanged':
            self.sigActiveImageChanged.emit(
                kwargs['previous'], kwargs['legend'])
        elif event == 'activeScatterChanged':
            self.sigActiveScatterChanged.emit(
                kwargs['previous'], kwargs['legend'])
        elif event == 'interactiveModeChanged':
            self.sigInteractiveModeChanged.emit(kwargs['source'])

        eventDict = kwargs.copy()
        eventDict['event'] = event
        self._callback(eventDict)

    def setCallback(self, callbackFunction=None):
        """Attach a listener to the backend.

        Limitation: Only one listener at a time.

        :param callbackFunction: function accepting a dictionary as input
                                 to handle the graph events
                                 If None (default), use a default listener.
        """
        # TODO allow multiple listeners
        # allow register listener by event type
        if callbackFunction is None:
            callbackFunction = WeakMethodProxy(self.graphCallback)
        self._callback = callbackFunction

    def graphCallback(self, ddict=None):
        """This callback is going to receive all the events from the plot.

        Those events will consist on a dictionary and among the dictionary
        keys the key 'event' is mandatory to describe the type of event.
        This default implementation only handles setting the active curve.
        """

        if ddict is None:
            ddict = {}
        _logger.debug("Received dict keys = %s", str(ddict.keys()))
        _logger.debug(str(ddict))
        if ddict['event'] in ["legendClicked", "curveClicked"]:
            if ddict['button'] == "left":
                self.setActiveCurve(ddict['label'])
                qt.QToolTip.showText(self.cursor().pos(), ddict['label'])
        elif ddict['event'] == 'mouseClicked' and ddict['button'] == 'left':
            self.setActiveCurve(None)

    def saveGraph(self, filename, fileFormat=None, dpi=None):
        """Save a snapshot of the plot.

        Supported file formats depends on the backend in use.
        The following file formats are always supported: "png", "svg".
        The matplotlib backend supports more formats:
        "pdf", "ps", "eps", "tiff", "jpeg", "jpg".

        :param filename: Destination
        :type filename: str, StringIO or BytesIO
        :param str fileFormat:  String specifying the format
        :return: False if cannot save the plot, True otherwise
        """
        if fileFormat is None:
            if not hasattr(filename, 'lower'):
                _logger.warning(
                    'saveGraph cancelled, cannot define file format.')
                return False
            else:
                fileFormat = (filename.split(".")[-1]).lower()

        supportedFormats = ("png", "svg", "pdf", "ps", "eps",
                            "tif", "tiff", "jpeg", "jpg")

        if fileFormat not in supportedFormats:
            _logger.warning('Unsupported format %s', fileFormat)
            return False
        else:
            self._backend.saveGraph(filename,
                                    fileFormat=fileFormat,
                                    dpi=dpi)
            return True

    def getDataMargins(self):
        """Get the default data margin ratios, see :meth:`setDataMargins`.

        :return: The margin ratios for each side (xMin, xMax, yMin, yMax).
        :rtype: A 4-tuple of floats.
        """
        return self._defaultDataMargins

    def setDataMargins(self, xMinMargin=0., xMaxMargin=0.,
                       yMinMargin=0., yMaxMargin=0.):
        """Set the default data margins to use in :meth:`resetZoom`.

        Set the default ratios of margins (as floats) to add around the data
        inside the plot area for each side.
        """
        self._defaultDataMargins = (xMinMargin, xMaxMargin,
                                    yMinMargin, yMaxMargin)

    def getAutoReplot(self):
        """Return True if replot is automatically handled, False otherwise.

        See :meth`setAutoReplot`.
        """
        return self._autoreplot

    def setAutoReplot(self, autoreplot=True):
        """Set automatic replot mode.

        When enabled, the plot is redrawn automatically when changed.
        When disabled, the plot is not redrawn when its content change.
        Instead, it :meth:`replot` must be called.

        :param bool autoreplot: True to enable it (default),
                                False to disable it.
        """
        self._autoreplot = bool(autoreplot)

        # If the plot is dirty before enabling autoreplot,
        # then _backend.postRedisplay will never be called from _setDirtyPlot
        if self._autoreplot and self._getDirtyPlot():
            self._backend.postRedisplay()

    def replot(self):
        """Redraw the plot immediately."""
        for item in self._contentToUpdate:
            item._update(self._backend)
        self._contentToUpdate = []
        self._backend.replot()
        self._dirty = False  # reset dirty flag

    def _forceResetZoom(self, dataMargins=None):
        """Reset the plot limits to the bounds of the data and redraw the plot.

        This method forces a reset zoom and does not check axis autoscale.

        Extra margins can be added around the data inside the plot area
        (see :meth:`setDataMargins`).
        Margins are given as one ratio of the data range per limit of the
        data (xMin, xMax, yMin and yMax limits).
        For log scale, extra margins are applied in log10 of the data.

        :param dataMargins: Ratios of margins to add around the data inside
                            the plot area for each side (default: no margins).
        :type dataMargins: A 4-tuple of float as (xMin, xMax, yMin, yMax).
        """
        if dataMargins is None:
            dataMargins = self._defaultDataMargins

        # Get data range
        ranges = self.getDataRange()
        xmin, xmax = (1., 100.) if ranges.x is None else ranges.x
        ymin, ymax = (1., 100.) if ranges.y is None else ranges.y
        if ranges.yright is None:
            ymin2, ymax2 = None, None
        else:
            ymin2, ymax2 = ranges.yright

        # Add margins around data inside the plot area
        newLimits = list(_utils.addMarginsToLimits(
            dataMargins,
            self._xAxis._isLogarithmic(),
            self._yAxis._isLogarithmic(),
            xmin, xmax, ymin, ymax, ymin2, ymax2))

        if self.isKeepDataAspectRatio():
            # Use limits with margins to keep ratio
            xmin, xmax, ymin, ymax = newLimits[:4]

            # Compute bbox wth figure aspect ratio
            plotWidth, plotHeight = self.getPlotBoundsInPixels()[2:]
            if plotWidth > 0 and plotHeight > 0:
                plotRatio = plotHeight / plotWidth
                dataRatio = (ymax - ymin) / (xmax - xmin)
                if dataRatio < plotRatio:
                    # Increase y range
                    ycenter = 0.5 * (ymax + ymin)
                    yrange = (xmax - xmin) * plotRatio
                    newLimits[2] = ycenter - 0.5 * yrange
                    newLimits[3] = ycenter + 0.5 * yrange

                elif dataRatio > plotRatio:
                    # Increase x range
                    xcenter = 0.5 * (xmax + xmin)
                    xrange_ = (ymax - ymin) / plotRatio
                    newLimits[0] = xcenter - 0.5 * xrange_
                    newLimits[1] = xcenter + 0.5 * xrange_

        self.setLimits(*newLimits)

    def resetZoom(self, dataMargins=None):
        """Reset the plot limits to the bounds of the data and redraw the plot.

        It automatically scale limits of axes that are in autoscale mode
        (see :meth:`getXAxis`, :meth:`getYAxis` and :meth:`Axis.setAutoScale`).
        It keeps current limits on axes that are not in autoscale mode.

        Extra margins can be added around the data inside the plot area
        (see :meth:`setDataMargins`).
        Margins are given as one ratio of the data range per limit of the
        data (xMin, xMax, yMin and yMax limits).
        For log scale, extra margins are applied in log10 of the data.

        :param dataMargins: Ratios of margins to add around the data inside
                            the plot area for each side (default: no margins).
        :type dataMargins: A 4-tuple of float as (xMin, xMax, yMin, yMax).
        """
        xLimits = self._xAxis.getLimits()
        yLimits = self._yAxis.getLimits()
        y2Limits = self._yRightAxis.getLimits()

        xAuto = self._xAxis.isAutoScale()
        yAuto = self._yAxis.isAutoScale()

        # With log axes, autoscale if limits are <= 0
        # This avoids issues with toggling log scale with matplotlib 2.1.0
        if self._xAxis.getScale() == self._xAxis.LOGARITHMIC and xLimits[0] <= 0:
            xAuto = True
        if self._yAxis.getScale() == self._yAxis.LOGARITHMIC and (yLimits[0] <= 0 or y2Limits[0] <= 0):
            yAuto = True

        if not xAuto and not yAuto:
            _logger.debug("Nothing to autoscale")
        else:  # Some axes to autoscale
            self._forceResetZoom(dataMargins=dataMargins)

            # Restore limits for axis not in autoscale
            if not xAuto and yAuto:
                self.setGraphXLimits(*xLimits)
            elif xAuto and not yAuto:
                if y2Limits is not None:
                    self.setGraphYLimits(
                        y2Limits[0], y2Limits[1], axis='right')
                if yLimits is not None:
                    self.setGraphYLimits(yLimits[0], yLimits[1], axis='left')

        if (xLimits != self._xAxis.getLimits() or
                yLimits != self._yAxis.getLimits() or
                y2Limits != self._yRightAxis.getLimits()):
            self._notifyLimitsChanged()

    # Coord conversion

    def dataToPixel(self, x=None, y=None, axis="left", check=True):
        """Convert a position in data coordinates to a position in pixels.

        :param float x: The X coordinate in data space. If None (default)
                        the middle position of the displayed data is used.
        :param float y: The Y coordinate in data space. If None (default)
                        the middle position of the displayed data is used.
        :param str axis: The Y axis to use for the conversion
                         ('left' or 'right').
        :param bool check: True to return None if outside displayed area,
                           False to convert to pixels anyway
        :returns: The corresponding position in pixels or
                  None if the data position is not in the displayed area and
                  check is True.
        :rtype: A tuple of 2 floats: (xPixel, yPixel) or None.
        """
        assert axis in ("left", "right")

        xmin, xmax = self._xAxis.getLimits()
        yAxis = self.getYAxis(axis=axis)
        ymin, ymax = yAxis.getLimits()

        if x is None:
            x = 0.5 * (xmax + xmin)
        if y is None:
            y = 0.5 * (ymax + ymin)

        if check:
            if x > xmax or x < xmin:
                return None

            if y > ymax or y < ymin:
                return None

        return self._backend.dataToPixel(x, y, axis=axis)

    def pixelToData(self, x, y, axis="left", check=False):
        """Convert a position in pixels to a position in data coordinates.

        :param float x: The X coordinate in pixels. If None (default)
                            the center of the widget is used.
        :param float y: The Y coordinate in pixels. If None (default)
                            the center of the widget is used.
        :param str axis: The Y axis to use for the conversion
                         ('left' or 'right').
        :param bool check: Toggle checking if pixel is in plot area.
                           If False, this method never returns None.
        :returns: The corresponding position in data space or
                  None if the pixel position is not in the plot area.
        :rtype: A tuple of 2 floats: (xData, yData) or None.
        """
        assert axis in ("left", "right")
        return self._backend.pixelToData(x, y, axis=axis, check=check)

    def getPlotBoundsInPixels(self):
        """Plot area bounds in widget coordinates in pixels.

        :return: bounds as a 4-tuple of int: (left, top, width, height)
        """
        return self._backend.getPlotBoundsInPixels()

    # Interaction support

    def setGraphCursorShape(self, cursor=None):
        """Set the cursor shape.

        :param str cursor: Name of the cursor shape
        """
        self._backend.setGraphCursorShape(cursor)

    def _pickMarker(self, x, y, test=None):
        """Pick a marker at the given position.

        To use for interaction implementation.

        :param float x: X position in pixels.
        :param float y: Y position in pixels.
        :param test: A callable to call for each picked marker to filter
                     picked markers. If None (default), do not filter markers.
        """
        if test is None:
            def test(mark):
                return True

        markers = self._backend.pickItems(x, y, kinds=('marker',))
        legends = [m['legend'] for m in markers if m['kind'] == 'marker']

        for legend in reversed(legends):
            marker = self._getMarker(legend)
            if marker is not None and test(marker):
                return marker
        return None

    def _getAllMarkers(self, just_legend=False):
        """Returns all markers' legend or objects

        :param bool just_legend: True to get the legend of the markers,
                                 False (the default) to get marker objects.
        :return: list of legend of list of marker objects
        :rtype: list of str or list of marker objects
        """
        return self._getItems(
            kind='marker', just_legend=just_legend, withhidden=True)

    def _getMarker(self, legend=None):
        """Get the object describing a specific marker.

        It returns None in case no matching marker is found

        :param str legend: The legend of the marker to retrieve
        :rtype: None of marker object
        """
        return self._getItem(kind='marker', legend=legend)

    def _pickImageOrCurve(self, x, y, test=None):
        """Pick an image or a curve at the given position.

        To use for interaction implementation.

        :param float x: X position in pixels
        :param float y: Y position in pixels
        :param test: A callable to call for each picked item to filter
                     picked items. If None (default), do not filter items.
        """
        if test is None:
            def test(i):
                return True

        allItems = self._backend.pickItems(x, y, kinds=('curve', 'image'))
        allItems = [item for item in allItems
                    if item['kind'] in ['curve', 'image']]

        for item in reversed(allItems):
            kind, legend = item['kind'], item['legend']
            if kind == 'curve':
                curve = self.getCurve(legend)
                if curve is not None and test(curve):
                    return kind, curve, item['indices']

            elif kind == 'image':
                image = self.getImage(legend)
                if image is not None and test(image):
                    return kind, image, None

            else:
                _logger.warning('Unsupported kind: %s', kind)

        return None

    def _pick(self, x, y):
        """Pick items in the plot at given position.

        :param float x: X position in pixels
        :param float y: Y position in pixels
        :return: Iterable of (plot item, indices) at picked position.
            Items are ordered from back to front.
        """
        items = []

        # Convert backend result to plot items
        for itemInfo in self._backend.pickItems(
                x, y, kinds=('marker', 'curve', 'image')):
            kind, legend = itemInfo['kind'], itemInfo['legend']

            if kind in ('marker', 'image'):
                item = self._getItem(kind=kind, legend=legend)
                indices = None  # TODO compute indices for images

            else:  # backend kind == 'curve'
                for kind in ('curve', 'histogram', 'scatter'):
                    item = self._getItem(kind=kind, legend=legend)
                    if item is not None:
                        indices = itemInfo['indices']
                        break
                else:
                    _logger.error(
                        'Cannot find corresponding picked item')
                    continue
            items.append((item, indices))

        return tuple(items)

    # User event handling #

    def _isPositionInPlotArea(self, x, y):
        """Project position in pixel to the closest point in the plot area

        :param float x: X coordinate in widget coordinate (in pixel)
        :param float y: Y coordinate in widget coordinate (in pixel)
        :return: (x, y) in widget coord (in pixel) in the plot area
        """
        left, top, width, height = self.getPlotBoundsInPixels()
        xPlot = numpy.clip(x, left, left + width)
        yPlot = numpy.clip(y, top, top + height)
        return xPlot, yPlot

    def onMousePress(self, xPixel, yPixel, btn):
        """Handle mouse press event.

        :param float xPixel: X mouse position in pixels
        :param float yPixel: Y mouse position in pixels
        :param str btn: Mouse button in 'left', 'middle', 'right'
        """
        if self._isPositionInPlotArea(xPixel, yPixel) == (xPixel, yPixel):
            self._pressedButtons.append(btn)
            self._eventHandler.handleEvent('press', xPixel, yPixel, btn)

    def onMouseMove(self, xPixel, yPixel):
        """Handle mouse move event.

        :param float xPixel: X mouse position in pixels
        :param float yPixel: Y mouse position in pixels
        """
        inXPixel, inYPixel = self._isPositionInPlotArea(xPixel, yPixel)
        isCursorInPlot = inXPixel == xPixel and inYPixel == yPixel

        if self._cursorInPlot != isCursorInPlot:
            self._cursorInPlot = isCursorInPlot
            self._eventHandler.handleEvent(
                'enter' if self._cursorInPlot else 'leave')

        if isCursorInPlot:
            # Signal mouse move event
            dataPos = self.pixelToData(inXPixel, inYPixel)
            assert dataPos is not None

            btn = self._pressedButtons[-1] if self._pressedButtons else None
            event = PlotEvents.prepareMouseSignal(
                'mouseMoved', btn, dataPos[0], dataPos[1], xPixel, yPixel)
            self.notify(**event)

        # Either button was pressed in the plot or cursor is in the plot
        if isCursorInPlot or self._pressedButtons:
            self._eventHandler.handleEvent('move', inXPixel, inYPixel)

    def onMouseRelease(self, xPixel, yPixel, btn):
        """Handle mouse release event.

        :param float xPixel: X mouse position in pixels
        :param float yPixel: Y mouse position in pixels
        :param str btn: Mouse button in 'left', 'middle', 'right'
        """
        try:
            self._pressedButtons.remove(btn)
        except ValueError:
            pass
        else:
            xPixel, yPixel = self._isPositionInPlotArea(xPixel, yPixel)
            self._eventHandler.handleEvent('release', xPixel, yPixel, btn)

    def onMouseWheel(self, xPixel, yPixel, angleInDegrees):
        """Handle mouse wheel event.

        :param float xPixel: X mouse position in pixels
        :param float yPixel: Y mouse position in pixels
        :param float angleInDegrees: Angle corresponding to wheel motion.
                                     Positive for movement away from the user,
                                     negative for movement toward the user.
        """
        if self._isPositionInPlotArea(xPixel, yPixel) == (xPixel, yPixel):
            self._eventHandler.handleEvent(
                'wheel', xPixel, yPixel, angleInDegrees)

    def onMouseLeaveWidget(self):
        """Handle mouse leave widget event."""
        if self._cursorInPlot:
            self._cursorInPlot = False
            self._eventHandler.handleEvent('leave')

    # Interaction modes #

    def getInteractiveMode(self):
        """Returns the current interactive mode as a dict.

        The returned dict contains at least the key 'mode'.
        Mode can be: 'draw', 'pan', 'select', 'zoom'.
        It can also contains extra keys (e.g., 'color') specific to a mode
        as provided to :meth:`setInteractiveMode`.
        """
        return self._eventHandler.getInteractiveMode()

    def setInteractiveMode(self, mode, color='black',
                           shape='polygon', label=None,
                           zoomOnWheel=True, source=None, width=None):
        """Switch the interactive mode.

        :param str mode: The name of the interactive mode.
                         In 'draw', 'pan', 'select', 'select-draw', 'zoom'.
        :param color: Only for 'draw' and 'zoom' modes.
                      Color to use for drawing selection area. Default black.
        :type color: Color description: The name as a str or
                     a tuple of 4 floats.
        :param str shape: Only for 'draw' mode. The kind of shape to draw.
                          In 'polygon', 'rectangle', 'line', 'vline', 'hline',
                          'freeline'.
                          Default is 'polygon'.
        :param str label: Only for 'draw' mode, sent in drawing events.
        :param bool zoomOnWheel: Toggle zoom on wheel support
        :param source: A user-defined object (typically the caller object)
                       that will be send in the interactiveModeChanged event,
                       to identify which object required a mode change.
                       Default: None
        :param float width: Width of the pencil. Only for draw pencil mode.
        """
        self._eventHandler.setInteractiveMode(mode, color, shape, label, width)
        self._eventHandler.zoomOnWheel = zoomOnWheel

        self.notify(
            'interactiveModeChanged', source=source)

    # Panning with arrow keys

    def isPanWithArrowKeys(self):
        """Returns whether or not panning the graph with arrow keys is enable.

        See :meth:`setPanWithArrowKeys`.
        """
        return self._panWithArrowKeys

    def setPanWithArrowKeys(self, pan=False):
        """Enable/Disable panning the graph with arrow keys.

        This grabs the keyboard.

        :param bool pan: True to enable panning, False to disable.
        """
        pan = bool(pan)
        panHasChanged = self._panWithArrowKeys != pan

        self._panWithArrowKeys = pan
        if not self._panWithArrowKeys:
            self.setFocusPolicy(qt.Qt.NoFocus)
        else:
            self.setFocusPolicy(qt.Qt.StrongFocus)
            self.setFocus(qt.Qt.OtherFocusReason)

        if panHasChanged:
            self.sigSetPanWithArrowKeys.emit(pan)

    # Dict to convert Qt arrow key code to direction str.
    _ARROWS_TO_PAN_DIRECTION = {
        qt.Qt.Key_Left: 'left',
        qt.Qt.Key_Right: 'right',
        qt.Qt.Key_Up: 'up',
        qt.Qt.Key_Down: 'down'
    }

    def keyPressEvent(self, event):
        """Key event handler handling panning on arrow keys.

        Overrides base class implementation.
        """
        key = event.key()
        if self._panWithArrowKeys and key in self._ARROWS_TO_PAN_DIRECTION:
            self.pan(self._ARROWS_TO_PAN_DIRECTION[key], factor=0.1)

            # Send a mouse move event to the plot widget to take into account
            # that even if mouse didn't move on the screen, it moved relative
            # to the plotted data.
            qapp = qt.QApplication.instance()
            event = qt.QMouseEvent(
                qt.QEvent.MouseMove,
                self.getWidgetHandle().mapFromGlobal(qt.QCursor.pos()),
                qt.Qt.NoButton,
                qapp.mouseButtons(),
                qapp.keyboardModifiers())
            qapp.sendEvent(self.getWidgetHandle(), event)

        else:
            # Only call base class implementation when key is not handled.
            # See QWidget.keyPressEvent for details.
            super(PlotWidget, self).keyPressEvent(event)