This file is indexed.

/usr/lib/python3/dist-packages/mpl_toolkits/axisartist/axis_artist.py is in python3-matplotlib 2.0.0+dfsg1-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
"""
axis_artist.py module provides axis-related artists. They are

 * axis line
 * tick lines
 * tick labels
 * axis label
 * grid lines

The main artist class is a AxisArtist and a GridlinesCollection. The
GridlinesCollection is responsible for drawing grid lines and the
AxisArtist is responsible for all other artists. The AxisArtist class
has attributes that are associated with each type of artists.

 * line : axis line
 * major_ticks : major tick lines
 * major_ticklabels : major tick labels
 * minor_ticks : minor tick lines
 * minor_ticklabels : minor tick labels
 * label : axis label

Typically, the AxisArtist associated with a axes will be accessed with
the *axis* dictionary of the axes, i.e., the AxisArtist for the bottom
axis is

  ax.axis["bottom"]

where *ax* is an instance of axes (mpl_toolkits.axislines.Axes).  Thus,
ax.axis["bottom"].line is an artist associated with the axis line, and
ax.axis["bottom"].major_ticks is an artist associated with the major tick
lines.

You can change the colors, fonts, line widths, etc. of these artists
by calling suitable set method. For example, to change the color of the major
ticks of the bottom axis to red,

  ax.axis["bottom"].major_ticks.set_color("r")

However, things like the locations of ticks, and their ticklabels need
to be changed from the side of the grid_helper.

axis_direction
--------------

AxisArtist, AxisLabel, TickLabels have *axis_direction* attribute,
which adjusts the location, angle, etc.,. The *axis_direction* must be
one of [left, right, bottom, top] and they follow the matplotlib
convention for the rectangle axis.

For example, for the *bottom* axis (the left and right is relative to
the direction of the increasing coordinate),

 * ticklabels and axislabel are on the right
 * ticklabels and axislabel have text angle of 0
 * ticklabels are baseline, center-aligned
 * axislabel is top, center-aligned


The text angles are actually relative to (90 + angle of the direction
to the ticklabel), which gives 0 for bottom axis.

                        left bottom right top
 ticklabels location    left right  right left
 axislabel location     left right  right left
 ticklabels angle       90    0      -90  180
 axislabel angle        180   0     0     180
 ticklabel va           center baseline center baseline
 axislabel va           center top      center bottom
 ticklabel ha           right  center   right  center
 axislabel ha           right  center   right  center


Ticks are by default direct opposite side of the ticklabels. To make
ticks to the same side of the ticklabels,

  ax.axis["bottom"].major_ticks.set_ticks_out(True)


Following attributes can be customized (use set_xxx method)

 * Ticks : ticksize, tick_out
 * TickLabels : pad
 * AxisLabel : pad

"""
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import six

# FIXME :

# * : angles are given in data coordinate - need to convert it to canvas coordinate


import matplotlib.axes as maxes
import matplotlib.artist as martist
import matplotlib.text as mtext
import matplotlib.font_manager as font_manager

from matplotlib.path import Path
from matplotlib.transforms import Affine2D, ScaledTranslation, \
     IdentityTransform, TransformedPath, Bbox
from matplotlib.collections import LineCollection

from matplotlib import rcParams

from matplotlib.artist import allow_rasterization

import warnings

import numpy as np


import matplotlib.lines as mlines
from .axisline_style import AxislineStyle


class BezierPath(mlines.Line2D):

    def __init__(self, path, *kl, **kw):
        mlines.Line2D.__init__(self, [], [], *kl, **kw)
        self._path = path
        self._invalid = False

    def recache(self):

        self._transformed_path = TransformedPath(self._path, self.get_transform())

        self._invalid = False

    def set_path(self, path):
        self._path = path
        self._invalid = True


    def draw(self, renderer):
        if self._invalid:
            self.recache()

        if not self._visible: return
        renderer.open_group('line2d')

        gc = renderer.new_gc()
        self._set_gc_clip(gc)

        gc.set_foreground(self._color)
        gc.set_antialiased(self._antialiased)
        gc.set_linewidth(self._linewidth)
        gc.set_alpha(self._alpha)
        if self.is_dashed():
            cap = self._dashcapstyle
            join = self._dashjoinstyle
        else:
            cap = self._solidcapstyle
            join = self._solidjoinstyle
        gc.set_joinstyle(join)
        gc.set_capstyle(cap)

        funcname = self._lineStyles.get(self._linestyle, '_draw_nothing')
        if funcname != '_draw_nothing':
            tpath, affine = self._transformed_path.get_transformed_path_and_affine()
            lineFunc = getattr(self, funcname)
            lineFunc(renderer, gc, tpath, affine.frozen())

        gc.restore()
        renderer.close_group('line2d')



class UnimplementedException(Exception):
    pass

from matplotlib.artist import Artist

class AttributeCopier(object):
    def __init__(self, ref_artist, klass=Artist):
        self._klass = klass
        self._ref_artist = ref_artist
        super(AttributeCopier, self).__init__()

    def set_ref_artist(self, artist):
        self._ref_artist = artist

    def get_ref_artist(self):
        raise RuntimeError("get_ref_artist must overridden")
    #return self._ref_artist

    def get_attribute_from_ref_artist(self, attr_name, default_value):
        get_attr_method_name = "get_"+attr_name
        c = getattr(self._klass, get_attr_method_name)(self)
        if c == 'auto':
            ref_artist = self.get_ref_artist()
            if ref_artist:
                attr = getattr(ref_artist,
                               get_attr_method_name)()
                return attr
            else:
                return default_value

        return c


from matplotlib.lines import Line2D

class Ticks(Line2D, AttributeCopier):
    """
    Ticks are derived from Line2D, and note that ticks themselves
    are markers. Thus, you should use set_mec, set_mew, etc.

    To change the tick size (length), you need to use
    set_ticksize. To change the direction of the ticks (ticks are
    in opposite direction of ticklabels by default), use
    set_tick_out(False).
    """

    def __init__(self, ticksize, tick_out=False, **kwargs):
        self._ticksize = ticksize
        self.locs_angles_labels = []

        self.set_tick_out(tick_out)

        self._axis = kwargs.pop("axis", None)
        if self._axis is not None:
            if "color" not in kwargs:
                kwargs["color"] = "auto"
            if ("mew" not in kwargs) and ("markeredgewidth" not in kwargs):
                kwargs["markeredgewidth"] = "auto"

        Line2D.__init__(self, [0.], [0.], **kwargs)
        AttributeCopier.__init__(self, self._axis, klass=Line2D)
        self.set_snap(True)

    def get_ref_artist(self):
        #return self._ref_artist.get_ticklines()[0]
        return self._ref_artist.majorTicks[0].tick1line

    def get_color(self):
        return self.get_attribute_from_ref_artist("color", "k")

    def get_markeredgecolor(self):
        if self._markeredgecolor == 'auto':
            return self.get_color()
        else:
            return self._markeredgecolor

    def get_markeredgewidth(self):
        return self.get_attribute_from_ref_artist("markeredgewidth", .5)


    def set_tick_out(self, b):
        """
        set True if tick need to be rotated by 180 degree.
        """
        self._tick_out = b

    def get_tick_out(self):
        """
        Return True if the tick will be rotated by 180 degree.
        """
        return self._tick_out


    def set_ticksize(self, ticksize):
        """
        set length of the ticks in points.
        """
        self._ticksize = ticksize


    def get_ticksize(self):
        """
        Return length of the ticks in points.
        """
        return self._ticksize

    def set_locs_angles(self, locs_angles):
        self.locs_angles = locs_angles


    def _update(self, renderer):
        pass

    _tickvert_path = Path([[0., 0.], [1., 0.]])

    def draw(self, renderer):
        if not self.get_visible():
            return

        self._update(renderer) # update the tick

        size = self._ticksize
        path_trans = self.get_transform()

        # set gc : copied from lines.py
#         gc = renderer.new_gc()
#         self._set_gc_clip(gc)

#         gc.set_foreground(self.get_color())
#         gc.set_antialiased(self._antialiased)
#         gc.set_linewidth(self._linewidth)
#         gc.set_alpha(self._alpha)
#         if self.is_dashed():
#             cap = self._dashcapstyle
#             join = self._dashjoinstyle
#         else:
#             cap = self._solidcapstyle
#             join = self._solidjoinstyle
#         gc.set_joinstyle(join)
#         gc.set_capstyle(cap)
#         gc.set_snap(self.get_snap())


        gc = renderer.new_gc()
        self._set_gc_clip(gc)
        gc.set_foreground(self.get_markeredgecolor())
        gc.set_linewidth(self.get_markeredgewidth())
        gc.set_alpha(self._alpha)

        offset = renderer.points_to_pixels(size)
        marker_scale = Affine2D().scale(offset, offset)

        if self.get_tick_out():
            add_angle = 180
        else:
            add_angle = 0

        marker_rotation = Affine2D()
        marker_transform = marker_scale + marker_rotation

        for loc, angle in self.locs_angles:
            marker_rotation.rotate_deg(angle+add_angle)
            locs = path_trans.transform_non_affine(np.array([loc, loc]))
            renderer.draw_markers(gc, self._tickvert_path, marker_transform,
                                  Path(locs), path_trans.get_affine())
            marker_rotation.clear()

        gc.restore()


def test_ticks():
    import matplotlib.pyplot as plt
    fig = plt.figure(1)
    fig.clf()
    ax = fig.add_subplot(111)
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ticks = Ticks(ticksize=10, axis=ax.xaxis)
    ax.add_artist(ticks)
    locs_angles = [((0.2, 0.), 90),
                          ((0.4, 0.), 120)]
    ticks.set_locs_angles(locs_angles)
    plt.draw()




class LabelBase(mtext.Text):
    """
    A base class for AxisLabel and TickLabels. The position and angle
    of the text are calculated by to offset_ref_angle,
    text_ref_angle, and offset_radius attributes.
    """

    def __init__(self, *kl, **kwargs):
        self.locs_angles_labels = []
        self._ref_angle = 0
        self._offset_radius = 0.

        super(LabelBase, self).__init__(*kl,
                                        **kwargs)

        self.set_rotation_mode("anchor")
        self._text_follow_ref_angle = True
        #self._offset_ref_angle = 0

    def _set_ref_angle(self, a):
        self._ref_angle = a

    def _get_ref_angle(self):
        return self._ref_angle

    def _get_text_ref_angle(self):
        if self._text_follow_ref_angle:
            return self._get_ref_angle()+90
        else:
            return 0 #self.get_ref_angle()

    def _get_offset_ref_angle(self):
        return self._get_ref_angle()

    def _set_offset_radius(self, offset_radius):
        self._offset_radius = offset_radius

    def _get_offset_radius(self):
        return self._offset_radius


    _get_opposite_direction = {"left":"right",
                               "right":"left",
                               "top":"bottom",
                               "bottom":"top"}.__getitem__


    def _update(self, renderer):
        pass

    def draw(self, renderer):
        if not self.get_visible(): return

        self._update(renderer)

        # save original and adjust some properties
        tr = self.get_transform()
        angle_orig = self.get_rotation()

        offset_tr = Affine2D()
        self.set_transform(tr+offset_tr)

        text_ref_angle = self._get_text_ref_angle()
        offset_ref_angle = self._get_offset_ref_angle()

        theta = (offset_ref_angle)/180.*np.pi
        dd = self._get_offset_radius()
        dx, dy = dd * np.cos(theta), dd * np.sin(theta)
        offset_tr.translate(dx, dy)
        self.set_rotation(text_ref_angle+angle_orig)
        super(LabelBase, self).draw(renderer)
        offset_tr.clear()


        # restore original properties
        self.set_transform(tr)
        self.set_rotation(angle_orig)


    def get_window_extent(self, renderer):

        self._update(renderer)

        # save original and adjust some properties
        tr = self.get_transform()
        angle_orig = self.get_rotation()

        offset_tr = Affine2D()
        self.set_transform(tr+offset_tr)

        text_ref_angle = self._get_text_ref_angle()
        offset_ref_angle = self._get_offset_ref_angle()

        theta = (offset_ref_angle)/180.*np.pi
        dd = self._get_offset_radius()
        dx, dy = dd * np.cos(theta), dd * np.sin(theta)
        offset_tr.translate(dx, dy)
        self.set_rotation(text_ref_angle+angle_orig)

        bbox = super(LabelBase, self).get_window_extent(renderer).frozen()

        offset_tr.clear()


        # restore original properties
        self.set_transform(tr)
        self.set_rotation(angle_orig)

        return bbox



def test_labelbase():
    import matplotlib.pyplot as plt
    fig = plt.figure(1)
    fig.clf()
    ax = fig.add_subplot(111)

    ax.plot([0.5], [0.5], "o")
    label = LabelBase(0.5, 0.5, "Test")

    a = -90
    label._set_ref_angle(a)
    label._set_offset_radius(offset_radius=50)
    label.set_rotation(-90)
    label.set(ha="center", va="top")

    ax.add_artist(label)
    plt.draw()









class AxisLabel(LabelBase, AttributeCopier):
    """
    Axis Label. Derived from Text. The position of the text is updated
    in the fly, so changing text position has no effect. Otherwise, the
    properties can be changed as a normal Text.

    To change the pad between ticklabels and axis label, use set_pad.
    """

    def __init__(self, *kl, **kwargs):

        axis_direction = kwargs.pop("axis_direction", "bottom")
        self._axis = kwargs.pop("axis", None)
        #super(AxisLabel, self).__init__(*kl, **kwargs)
        LabelBase.__init__(self, *kl, **kwargs)
        AttributeCopier.__init__(self, self._axis, klass=LabelBase)

        self.set_axis_direction(axis_direction)
        self._pad = 5
        self._extra_pad = 0

    def set_pad(self, pad):
        """
        Set the pad in points. Note that the actual pad will be the
        sum of the internal pad and the external pad (that are set
        automatically by the AxisArtist), and it only set the internal
        pad
        """
        self._pad = pad

    def get_pad(self):
        """
        return pad in points. See set_pad for more details.
        """
        return self._pad


    def _set_external_pad(self, p):
        """
        Set external pad IN PIXELS. This is intended to be set by the
        AxisArtist, bot by user..
        """
        self._extra_pad = p

    def _get_external_pad(self):
        """
        Get external pad.
        """
        return self._extra_pad


    def get_ref_artist(self):
        return self._axis.get_label()


    def get_text(self):
        t = super(AxisLabel, self).get_text()
        if t == "__from_axes__":
            return self._axis.get_label().get_text()
        return self._text

    _default_alignments = dict(left=("bottom", "center"),
                               right=("top", "center"),
                               bottom=("top", "center"),
                               top=("bottom", "center"))



    def set_default_alignment(self, d):
        if d not in ["left", "right", "top", "bottom"]:
            raise ValueError('direction must be on of "left", "right", "top", "bottom"')

        va, ha = self._default_alignments[d]
        self.set_va(va)
        self.set_ha(ha)


    _default_angles = dict(left=180,
                           right=0,
                           bottom=0,
                           top=180)


    def set_default_angle(self, d):
        if d not in ["left", "right", "top", "bottom"]:
            raise ValueError('direction must be on of "left", "right", "top", "bottom"')

        self.set_rotation(self._default_angles[d])


    def set_axis_direction(self, d):
        """
        Adjust the text angle and text alignment of axis label
        according to the matplotlib convention.


        =====================    ========== ========= ========== ==========
        property                 left       bottom    right      top
        =====================    ========== ========= ========== ==========
        axislabel angle          180        0         0          180
        axislabel va             center     top       center     bottom
        axislabel ha             right      center    right      center
        =====================    ========== ========= ========== ==========

        Note that the text angles are actually relative to (90 + angle
        of the direction to the ticklabel), which gives 0 for bottom
        axis.

        """
        if d not in ["left", "right", "top", "bottom"]:
            raise ValueError('direction must be on of "left", "right", "top", "bottom"')

        self.set_default_alignment(d)
        self.set_default_angle(d)

    def get_color(self):
        return self.get_attribute_from_ref_artist("color", "k")

    def draw(self, renderer):
        if not self.get_visible():
            return

        pad = renderer.points_to_pixels(self.get_pad())
        r = self._get_external_pad() + pad
        self._set_offset_radius(r)

        super(AxisLabel, self).draw(renderer)


    def get_window_extent(self, renderer):

        if not self.get_visible():
            return

        pad = renderer.points_to_pixels(self.get_pad())
        r = self._get_external_pad() + pad
        self._set_offset_radius(r)

        bb = super(AxisLabel, self).get_window_extent(renderer)

        return bb


class TickLabels(AxisLabel, AttributeCopier): # mtext.Text
    """
    Tick Labels. While derived from Text, this single artist draws all
    ticklabels. As in AxisLabel, the position of the text is updated
    in the fly, so changing text position has no effect. Otherwise,
    the properties can be changed as a normal Text. Unlike the
    ticklabels of the mainline matplotlib, properties of single
    ticklabel alone cannot modified.

    To change the pad between ticks and ticklabels, use set_pad.
    """

    def __init__(self, **kwargs):

        axis_direction = kwargs.pop("axis_direction", "bottom")
        AxisLabel.__init__(self, **kwargs)
        self.set_axis_direction(axis_direction)
        #self._axis_direction = axis_direction
        self._axislabel_pad = 0
        #self._extra_pad = 0


    # attribute copier
    def get_ref_artist(self):
        return self._axis.get_ticklabels()[0]

    def set_axis_direction(self, label_direction):
        """
        Adjust the text angle and text alignment of ticklabels
        according to the matplotlib convention.

        The *label_direction* must be one of [left, right, bottom,
        top].

        =====================    ========== ========= ========== ==========
        property                 left       bottom    right      top
        =====================    ========== ========= ========== ==========
        ticklabels angle         90         0         -90        180
        ticklabel va             center     baseline  center     baseline
        ticklabel ha             right      center    right      center
        =====================    ========== ========= ========== ==========


        Note that the text angles are actually relative to (90 + angle
        of the direction to the ticklabel), which gives 0 for bottom
        axis.

        """

        if label_direction not in ["left", "right", "top", "bottom"]:
            raise ValueError('direction must be one of "left", "right", "top", "bottom"')

        self._axis_direction = label_direction
        self.set_default_alignment(label_direction)
        self.set_default_angle(label_direction)


    def invert_axis_direction(self):
        label_direction = self._get_opposite_direction(self._axis_direction)
        self.set_axis_direction(label_direction)

    def _get_ticklabels_offsets(self, renderer, label_direction):
        """
        Calculates the offsets of the ticklabels from the tick and
        their total heights. The offset only takes account the offset
        due to the vertical alignment of the ticklabels, i.e.,if axis
        direction is bottom and va is ;top', it will return 0. if va
        is 'baseline', it will return (height-descent).
        """
        whd_list = self.get_texts_widths_heights_descents(renderer)

        if not whd_list:
            return 0, 0

        r = 0
        va, ha = self.get_va(), self.get_ha()

        if label_direction == "left":
            pad = max([w for (w, h, d) in whd_list])
            if ha == "left":
                r = pad
            elif ha == "center":
                r = .5 * pad
        elif label_direction == "right":
            pad = max([w for (w, h, d) in whd_list])
            if ha == "right":
                r = pad
            elif ha == "center":
                r = .5 * pad
        elif label_direction == "bottom":
            pad = max([h for (w, h, d) in whd_list])
            if va == "bottom":
                r = pad
            elif va == "center":
                r =.5 * pad
            elif va == "baseline":
                max_ascent = max([(h-d) for (w, h, d) in whd_list])
                max_descent = max([d for (w, h, d) in whd_list])
                r  = max_ascent
                pad = max_ascent + max_descent
        elif label_direction == "top":
            pad = max([h for (w, h, d) in whd_list])
            if va == "top":
                r = pad
            elif va == "center":
                r =.5 * pad
            elif va == "baseline":
                max_ascent = max([(h-d) for (w, h, d) in whd_list])
                max_descent = max([d for (w, h, d) in whd_list])
                r  = max_descent
                pad = max_ascent + max_descent

        #tick_pad = renderer.points_to_pixels(self.get_pad())

        # r : offset

        # pad : total height of the ticklabels. This will be used to
        # calculate the pad for the axislabel.
        return r, pad



    _default_alignments = dict(left=("center", "right"),
                               right=("center", "left"),
                               bottom=("baseline", "center"),
                               top=("baseline", "center"))



    # set_default_alignments(self, d)

    _default_angles = dict(left=90,
                           right=-90,
                           bottom=0,
                           top=180)


    def draw(self, renderer):
        if not self.get_visible():
            self._axislabel_pad = self._get_external_pad()
            return

        r, total_width = self._get_ticklabels_offsets(renderer,
                                                      self._axis_direction)

        #self._set_external_pad(r+self._get_external_pad())
        pad = self._get_external_pad() + \
              renderer.points_to_pixels(self.get_pad())
        self._set_offset_radius(r+pad)

        #self._set_offset_radius(r)

        for (x, y), a, l in self._locs_angles_labels:
            if not l.strip(): continue
            self._set_ref_angle(a) #+ add_angle
            self.set_x(x)
            self.set_y(y)
            self.set_text(l)
            LabelBase.draw(self, renderer)

        self._axislabel_pad = total_width \
                              + pad # the value saved will be used to draw axislabel.


    def set_locs_angles_labels(self, locs_angles_labels):
        self._locs_angles_labels = locs_angles_labels

    def get_window_extents(self, renderer):

        if not self.get_visible():
            self._axislabel_pad = self._get_external_pad()
            return []

        bboxes = []

        r, total_width = self._get_ticklabels_offsets(renderer,
                                                     self._axis_direction)

        pad = self._get_external_pad() + \
              renderer.points_to_pixels(self.get_pad())
        self._set_offset_radius(r+pad)


        for (x, y), a, l in self._locs_angles_labels:
            self._set_ref_angle(a) #+ add_angle
            self.set_x(x)
            self.set_y(y)
            self.set_text(l)
            bb = LabelBase.get_window_extent(self, renderer)
            bboxes.append(bb)

        self._axislabel_pad = total_width \
                              + pad # the value saved will be used to draw axislabel.

        return bboxes


    def get_texts_widths_heights_descents(self, renderer):
        """
        return a list of width, height, descent for ticklabels.
        """
        whd_list = []
        for (x, y), a, l in self._locs_angles_labels:
            if not l.strip(): continue
            clean_line, ismath = self.is_math_text(l)
            whd = renderer.get_text_width_height_descent(
                clean_line, self._fontproperties, ismath=ismath)
            whd_list.append(whd)

        return whd_list



def test_ticklabels():
    import matplotlib.pyplot as plt
    fig = plt.figure(1)
    fig.clf()
    ax = fig.add_subplot(111)
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ax.plot([0.2, 0.4], [0.5, 0.5], "o")
    ticks = Ticks(ticksize=10, axis=ax.xaxis)
    ax.add_artist(ticks)
    locs_angles_labels = [((0.2, 0.5), -90, "0.2"),
                          ((0.4, 0.5), -120, "0.4")]
    tick_locs_angles = [(xy, a+180) for xy, a, l in locs_angles_labels]
    ticks.set_locs_angles(tick_locs_angles)


    ax.plot([0.5], [0.5], ",")
    axislabel = AxisLabel(0.5, 0.5, "Test")
    axislabel._set_offset_radius(20)
    axislabel._set_ref_angle(0)
    axislabel.set_axis_direction("bottom")
    #axislabel._text_follow_ref_angle = True
    #axislabel.set(va="center", ha="right")
    ax.add_artist(axislabel)

    if 1:
        ticklabels = TickLabels(axis_direction="left")
        ticklabels._locs_angles_labels = locs_angles_labels
        #ticklabels.set_rotation(90)
        ticklabels.set_pad(10)

        ax.add_artist(ticklabels)

    ax.set_xlim(0, 1); ax.set_ylim(0, 1)

    plt.draw()




class GridlinesCollection(LineCollection):
    def __init__(self, *kl, **kwargs):
        """
        *which* : "major" or "minor"
        *axis* : "both", "x" or "y"
        """
        self._which = kwargs.pop("which", "major")
        self._axis = kwargs.pop("axis", "both")
        super(GridlinesCollection, self).__init__(*kl, **kwargs)
        self.set_grid_helper(None)

    def set_which(self, which):
        self._which = which

    def set_axis(self, axis):
        self._axis = axis

    def set_grid_helper(self, grid_helper):
        self._grid_helper = grid_helper

    def draw(self, renderer):
        if self._grid_helper is not None:
            self._grid_helper.update_lim(self.axes)
            gl = self._grid_helper.get_gridlines(self._which, self._axis)
            if gl:
                self.set_segments([np.transpose(l) for l in gl])
            else:
                self.set_segments([])
        super(GridlinesCollection, self).draw(renderer)




class AxisArtist(martist.Artist):
    """
    An artist which draws axis (a line along which the n-th axes coord
    is constant) line, ticks, ticklabels, and axis label.
    """

    ZORDER=2.5

    # LABELPAD : as property
    def _set_labelpad(self, v):
        return self.label.set_pad(v)

    def _get_labelpad(self):
        return self.label.get_pad()

    LABELPAD = property(_get_labelpad, _set_labelpad)

    def __init__(self, axes,
                 helper,
                 offset=None,
                 axis_direction="bottom",
                 **kw):
        """
        *axes* : axes
        *helper* : an AxisArtistHelper instance.
        """
        #axes is also used to follow the axis attribute (tick color, etc).

        super(AxisArtist, self).__init__(**kw)

        self.axes = axes

        self._axis_artist_helper = helper

        if offset is None:
            offset = (0, 0)
        self.dpi_transform = Affine2D()
        self.offset_transform = ScaledTranslation(offset[0], offset[1],
                                                  self.dpi_transform)

        self._label_visible = True
        self._majortick_visible = True
        self._majorticklabel_visible = True
        self._minortick_visible = True
        self._minorticklabel_visible = True


        #if self._axis_artist_helper._loc in ["left", "right"]:
        if axis_direction in ["left", "right"]:
            axis_name = "ytick"
            self.axis = axes.yaxis
        else:
            axis_name = "xtick"
            self.axis = axes.xaxis


        self._axisline_style = None


        self._axis_direction = axis_direction


        self._init_line()
        self._init_ticks(axis_name, **kw)
        self._init_offsetText(axis_direction)
        self._init_label()

        self.set_zorder(self.ZORDER)

        self._rotate_label_along_line = False

        # axis direction
        self._tick_add_angle = 180.
        self._ticklabel_add_angle = 0.
        self._axislabel_add_angle = 0.
        self.set_axis_direction(axis_direction)


    # axis direction

    def set_axis_direction(self, axis_direction):
        """
        Adjust the direction, text angle, text alignment of
        ticklabels, labels following the matplotlib convention for
        the rectangle axes.

        The *axis_direction* must be one of [left, right, bottom,
        top].

        =====================    ========== ========= ========== ==========
        property                 left       bottom    right      top
        =====================    ========== ========= ========== ==========
        ticklabels location      "-"        "+"       "+"        "-"
        axislabel location       "-"        "+"       "+"        "-"
        ticklabels angle         90         0         -90        180
        ticklabel va             center     baseline  center     baseline
        ticklabel ha             right      center    right      center
        axislabel angle          180        0         0          180
        axislabel va             center     top       center     bottom
        axislabel ha             right      center    right      center
        =====================    ========== ========= ========== ==========


        Note that the direction "+" and "-" are relative to the direction of
        the increasing coordinate. Also, the text angles are actually
        relative to (90 + angle of the direction to the ticklabel),
        which gives 0 for bottom axis.

        """

        if axis_direction not in ["left", "right", "top", "bottom"]:
            raise ValueError('direction must be on of "left", "right", "top", "bottom"')
        self._axis_direction = axis_direction
        if axis_direction in ["left", "top"]:
            #self._set_tick_direction("+")
            self.set_ticklabel_direction("-")
            self.set_axislabel_direction("-")
        else:
            #self._set_tick_direction("-")
            self.set_ticklabel_direction("+")
            self.set_axislabel_direction("+")

        self.major_ticklabels.set_axis_direction(axis_direction)
        self.label.set_axis_direction(axis_direction)

    # def _set_tick_direction(self, d):
    #     if d not in ["+", "-"]:
    #         raise ValueError('direction must be on of "in", "out"')

    #     if d == "+":
    #         self._tick_add_angle = 0 #get_helper()._extremes=0, 10
    #     else:
    #         self._tick_add_angle = 180 #get_helper()._extremes=0, 10

    def set_ticklabel_direction(self, tick_direction):
        """
        Adjust the direction of the ticklabel.

         ACCEPTS: [ "+" | "-" ]

        Note that the label_direction '+' and '-' are relative to the
        direction of the increasing coordinate.
        """

        if tick_direction not in ["+", "-"]:
            raise ValueError('direction must be one of "+", "-"')

        if tick_direction == "-":
            self._ticklabel_add_angle = 180
        else:
            self._ticklabel_add_angle = 0

    def invert_ticklabel_direction(self):
        self._ticklabel_add_angle = (self._ticklabel_add_angle + 180) % 360
        self.major_ticklabels.invert_axis_direction()
        self.minor_ticklabels.invert_axis_direction()

    # def invert_ticks_direction(self):
    #     self.major_ticks.set_tick_out(not self.major_ticks.get_tick_out())
    #     self.minor_ticks.set_tick_out(not self.minor_ticks.get_tick_out())

    def set_axislabel_direction(self, label_direction):
        """
        Adjust the direction of the axislabel.

         ACCEPTS: [ "+" | "-" ]

        Note that the label_direction '+' and '-' are relative to the
        direction of the increasing coordinate.
        """
        if label_direction not in ["+", "-"]:
            raise ValueError('direction must be one of "+", "-"')

        if label_direction == "-":
            self._axislabel_add_angle = 180
        else:
            self._axislabel_add_angle = 0



    def get_transform(self):
        return self.axes.transAxes + self.offset_transform

    def get_helper(self):
        """
        Return axis artist helper instance.
        """
        return self._axis_artist_helper


    def set_axisline_style(self, axisline_style=None, **kw):
        """
        Set the axisline style.

        *axisline_style* can be a string with axisline style name with optional
         comma-separated attributes. Alternatively, the attrs can
         be provided as keywords.

         set_arrowstyle("->,size=1.5")
         set_arrowstyle("->", size=1.5)

        Old attrs simply are forgotten.

        Without argument (or with arrowstyle=None), return
        available styles as a list of strings.
        """

        if axisline_style==None:
            return AxislineStyle.pprint_styles()

        if isinstance(axisline_style, AxislineStyle._Base):
            self._axisline_style = axisline_style
        else:
            self._axisline_style = AxislineStyle(axisline_style, **kw)


        self._init_line()


    def get_axisline_style(self):
        """
        return the current axisline style.
        """
        return self._axisline_style

    def _init_line(self):
        """
        Initialize the *line* artist that is responsible to draw the axis line.
        """
        tran = self._axis_artist_helper.get_line_transform(self.axes) \
               + self.offset_transform

        axisline_style = self.get_axisline_style()
        if axisline_style is None:
            self.line = BezierPath(self._axis_artist_helper.get_line(self.axes),
                                   color=rcParams['axes.edgecolor'],
                                   linewidth=rcParams['axes.linewidth'],
                                   transform=tran)
        else:
            self.line = axisline_style(self, transform=tran)

    def _draw_line(self, renderer):
        self.line.set_path(self._axis_artist_helper.get_line(self.axes))
        if self.get_axisline_style() is not None:
            self.line.set_line_mutation_scale(self.major_ticklabels.get_size())
        self.line.draw(renderer)


    def _init_ticks(self, axis_name, **kw):

        trans=self._axis_artist_helper.get_tick_transform(self.axes) \
               + self.offset_transform


        major_tick_size = kw.get("major_tick_size",
                                 rcParams['%s.major.size'%axis_name])
        major_tick_pad = kw.get("major_tick_pad",
                                rcParams['%s.major.pad'%axis_name])
        minor_tick_size = kw.get("minor_tick_size",
                                 rcParams['%s.minor.size'%axis_name])
        minor_tick_pad = kw.get("minor_tick_pad",
                                rcParams['%s.minor.pad'%axis_name])

        self.major_ticks = Ticks(major_tick_size,
                                 axis=self.axis,
                                 transform=trans)
        self.minor_ticks = Ticks(minor_tick_size,
                                 axis=self.axis,
                                 transform=trans)

        if axis_name == "xaxis":
            size = rcParams['xtick.labelsize']
        else:
            size = rcParams['ytick.labelsize']


        fontprops = font_manager.FontProperties(size=size)

        self.major_ticklabels = TickLabels(size=size, axis=self.axis,
                                           axis_direction=self._axis_direction)
        self.minor_ticklabels = TickLabels(size=size, axis=self.axis,
                                           axis_direction=self._axis_direction)


        self.major_ticklabels.set(figure = self.axes.figure,
                                  transform=trans,
                                  fontproperties=fontprops)
        self.major_ticklabels.set_pad(major_tick_pad)

        self.minor_ticklabels.set(figure = self.axes.figure,
                                  transform=trans,
                                  fontproperties=fontprops)
        self.minor_ticklabels.set_pad(minor_tick_pad)



    def _get_tick_info(self, tick_iter):
        """
        return ticks_loc_angle, ticklabels_loc_angle_label

        ticks_loc_angle : list of locs and angles for ticks
        ticklabels_loc_angle_label : list of locs, angles and labels for tickslabels
        """
        ticks_loc_angle = []
        ticklabels_loc_angle_label = []

        tick_add_angle = self._tick_add_angle
        ticklabel_add_angle = self._ticklabel_add_angle

        for loc, angle_normal, angle_tangent, label in tick_iter:
            angle_label = angle_tangent  - 90
            angle_label += ticklabel_add_angle

            if np.cos((angle_label - angle_normal)/180.*np.pi) < 0.:
                angle_tick = angle_normal
            else:
                angle_tick = angle_normal + 180

            ticks_loc_angle.append([loc, angle_tick])
            ticklabels_loc_angle_label.append([loc, angle_label, label])

        return ticks_loc_angle, ticklabels_loc_angle_label


    def _update_ticks(self, renderer):


        # set extra pad for major and minor ticklabels:
        # use ticksize of majorticks even for minor ticks. not clear what is best.

        dpi_cor = renderer.points_to_pixels(1.)
        if self.major_ticks.get_visible() and self.major_ticks.get_tick_out():
            self.major_ticklabels._set_external_pad(self.major_ticks._ticksize*dpi_cor)
            self.minor_ticklabels._set_external_pad(self.major_ticks._ticksize*dpi_cor)
        else:
            self.major_ticklabels._set_external_pad(0)
            self.minor_ticklabels._set_external_pad(0)


        majortick_iter,  minortick_iter = \
                self._axis_artist_helper.get_tick_iterators(self.axes)

        tick_loc_angle, ticklabel_loc_angle_label \
                              = self._get_tick_info(majortick_iter)

        self.major_ticks.set_locs_angles(tick_loc_angle)
        self.major_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)

        #self.major_ticks.draw(renderer)
        #self.major_ticklabels.draw(renderer)


        # minor ticks
        tick_loc_angle, ticklabel_loc_angle_label \
                              = self._get_tick_info(minortick_iter)

        self.minor_ticks.set_locs_angles(tick_loc_angle)
        self.minor_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)

        #self.minor_ticks.draw(renderer)
        #self.minor_ticklabels.draw(renderer)


        #if (self.major_ticklabels.get_visible() or self.minor_ticklabels.get_visible()):
        #    self._draw_offsetText(renderer)

        return self.major_ticklabels.get_window_extents(renderer)


    def _draw_ticks(self, renderer):

        extents = self._update_ticks(renderer)

        self.major_ticks.draw(renderer)
        self.major_ticklabels.draw(renderer)

        self.minor_ticks.draw(renderer)
        self.minor_ticklabels.draw(renderer)


        if (self.major_ticklabels.get_visible() or self.minor_ticklabels.get_visible()):
            self._draw_offsetText(renderer)

        return extents

    def _draw_ticks2(self, renderer):


        # set extra pad for major and minor ticklabels:
        # use ticksize of majorticks even for minor ticks. not clear what is best.

        dpi_cor = renderer.points_to_pixels(1.)
        if self.major_ticks.get_visible() and self.major_ticks.get_tick_out():
            self.major_ticklabels._set_external_pad(self.major_ticks._ticksize*dpi_cor)
            self.minor_ticklabels._set_external_pad(self.major_ticks._ticksize*dpi_cor)
        else:
            self.major_ticklabels._set_external_pad(0)
            self.minor_ticklabels._set_external_pad(0)


        majortick_iter,  minortick_iter = \
                self._axis_artist_helper.get_tick_iterators(self.axes)

        tick_loc_angle, ticklabel_loc_angle_label \
                              = self._get_tick_info(majortick_iter)

        self.major_ticks.set_locs_angles(tick_loc_angle)
        self.major_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)

        self.major_ticks.draw(renderer)
        self.major_ticklabels.draw(renderer)


        # minor ticks
        tick_loc_angle, ticklabel_loc_angle_label \
                              = self._get_tick_info(minortick_iter)

        self.minor_ticks.set_locs_angles(tick_loc_angle)
        self.minor_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)

        self.minor_ticks.draw(renderer)
        self.minor_ticklabels.draw(renderer)


        if (self.major_ticklabels.get_visible() or self.minor_ticklabels.get_visible()):
            self._draw_offsetText(renderer)

        return self.major_ticklabels.get_window_extents(renderer)




    _offsetText_pos = dict(left=(0, 1, "bottom", "right"),
                           right=(1, 1, "bottom", "left"),
                           bottom=(1, 0, "top", "right"),
                           top=(1, 1, "bottom", "right"))

    def _init_offsetText(self, direction):

        x,y,va,ha = self._offsetText_pos[direction]

        self.offsetText = mtext.Annotation("",
                                           xy=(x,y), xycoords="axes fraction",
                                           xytext=(0,0), textcoords="offset points",
                                           #fontproperties = fp,
                                           color = rcParams['xtick.color'],
                                           verticalalignment=va,
                                           horizontalalignment=ha,
                                           )
        self.offsetText.set_transform(IdentityTransform())
        self.axes._set_artist_props(self.offsetText)


    def _update_offsetText(self):
        self.offsetText.set_text( self.axis.major.formatter.get_offset() )
        self.offsetText.set_size(self.major_ticklabels.get_size())
        offset = self.major_ticklabels.get_pad() + self.major_ticklabels.get_size() + 2.
        self.offsetText.xyann= (0, offset)


    def _draw_offsetText(self, renderer):
        self._update_offsetText()
        self.offsetText.draw(renderer)



    def _init_label(self, **kw):
        # x in axes coords, y in display coords (to be updated at draw
        # time by _update_label_positions)

        labelsize = kw.get("labelsize",
                           rcParams['axes.labelsize'])
        #labelcolor = kw.get("labelcolor",
        #                    rcParams['axes.labelcolor'])
        fontprops = font_manager.FontProperties(
            size=labelsize,
            weight=rcParams['axes.labelweight'])
        textprops = dict(fontproperties = fontprops)
                         #color = labelcolor)

        tr = self._axis_artist_helper.get_axislabel_transform(self.axes) \
             + self.offset_transform

        self.label = AxisLabel(0, 0, "__from_axes__",
                               color = "auto", #rcParams['axes.labelcolor'],
                               fontproperties=fontprops,
                               axis=self.axis,
                               transform=tr,
                               axis_direction=self._axis_direction,
                               )

        self.label.set_figure(self.axes.figure)

        labelpad = kw.get("labelpad", 5)
        self.label.set_pad(labelpad)


    def _update_label(self, renderer):

        if not self.label.get_visible():
            return

        fontprops = font_manager.FontProperties(
            size=rcParams['axes.labelsize'],
            weight=rcParams['axes.labelweight'])

        #pad_points = self.major_tick_pad

        #print self._ticklabel_add_angle - self._axislabel_add_angle
        #if abs(self._ticklabel_add_angle - self._axislabel_add_angle)%360 > 90:
        if self._ticklabel_add_angle !=  self._axislabel_add_angle:
            if (self.major_ticks.get_visible() and not self.major_ticks.get_tick_out()) \
               or \
               (self.minor_ticks.get_visible() and not self.major_ticks.get_tick_out()):
                axislabel_pad = self.major_ticks._ticksize
            else:
                axislabel_pad = 0
        else:
            axislabel_pad = max([self.major_ticklabels._axislabel_pad,
                                 self.minor_ticklabels._axislabel_pad])


        #label_offset =  axislabel_pad + self.LABELPAD

        #self.label._set_offset_radius(label_offset)
        self.label._set_external_pad(axislabel_pad)

        xy, angle_tangent = self._axis_artist_helper.get_axislabel_pos_angle(self.axes)
        if xy is None: return

        angle_label = angle_tangent  - 90


        x, y = xy
        self.label._set_ref_angle(angle_label+self._axislabel_add_angle)
        self.label.set(x=x, y=y)


    def _draw_label(self, renderer):
        self._update_label(renderer)
        self.label.draw(renderer)

    def _draw_label2(self, renderer):

        if not self.label.get_visible():
            return

        fontprops = font_manager.FontProperties(
            size=rcParams['axes.labelsize'],
            weight=rcParams['axes.labelweight'])

        #pad_points = self.major_tick_pad

        #print self._ticklabel_add_angle - self._axislabel_add_angle
        #if abs(self._ticklabel_add_angle - self._axislabel_add_angle)%360 > 90:
        if self._ticklabel_add_angle !=  self._axislabel_add_angle:
            if (self.major_ticks.get_visible() and not self.major_ticks.get_tick_out()) \
               or \
               (self.minor_ticks.get_visible() and not self.major_ticks.get_tick_out()):
                axislabel_pad = self.major_ticks._ticksize
            else:
                axislabel_pad = 0
        else:
            axislabel_pad = max([self.major_ticklabels._axislabel_pad,
                                 self.minor_ticklabels._axislabel_pad])


        #label_offset =  axislabel_pad + self.LABELPAD

        #self.label._set_offset_radius(label_offset)
        self.label._set_external_pad(axislabel_pad)

        xy, angle_tangent = self._axis_artist_helper.get_axislabel_pos_angle(self.axes)
        if xy is None: return

        angle_label = angle_tangent  - 90


        x, y = xy
        self.label._set_ref_angle(angle_label+self._axislabel_add_angle)
        self.label.set(x=x, y=y)
        self.label.draw(renderer)



    def set_label(self, s):
        self.label.set_text(s)



    def get_tightbbox(self, renderer):
        if not self.get_visible(): return

        self._axis_artist_helper.update_lim(self.axes)

        dpi_cor = renderer.points_to_pixels(1.)
        self.dpi_transform.clear().scale(dpi_cor, dpi_cor)


        bb = []

        self._update_ticks(renderer)

        #if self.major_ticklabels.get_visible():
        bb.extend(self.major_ticklabels.get_window_extents(renderer))
        #if self.minor_ticklabels.get_visible():
        bb.extend(self.minor_ticklabels.get_window_extents(renderer))


        self._update_label(renderer)

        #if self.label.get_visible():
        bb.append(self.label.get_window_extent(renderer))
        bb.append(self.offsetText.get_window_extent(renderer))

        bb = [b for b in bb if b and (b.width!=0 or b.height!=0)]
        if bb:
            _bbox = Bbox.union(bb)
            return _bbox
        else:
            return None

        #self._draw_line(renderer)

        #self._draw_ticks(renderer)

        #self._draw_offsetText(renderer)
        #self._draw_label(renderer)



    @allow_rasterization
    def draw(self, renderer):
        'Draw the axis lines, tick lines and labels'

        if not self.get_visible(): return

        renderer.open_group(__name__)

        self._axis_artist_helper.update_lim(self.axes)

        dpi_cor = renderer.points_to_pixels(1.)
        self.dpi_transform.clear().scale(dpi_cor, dpi_cor)


        self._draw_ticks(renderer)

        self._draw_line(renderer)

        #self._draw_offsetText(renderer)
        self._draw_label(renderer)

        renderer.close_group(__name__)

    #def get_ticklabel_extents(self, renderer):
    #    pass

    def toggle(self, all=None, ticks=None, ticklabels=None, label=None):
        """
        Toggle visibility of ticks, ticklabels, and (axis) label.
        To turn all off, ::

          axis.toggle(all=False)

        To turn all off but ticks on ::

          axis.toggle(all=False, ticks=True)

        To turn all on but (axis) label off ::

          axis.toggle(all=True, label=False))

        """
        if all:
            _ticks, _ticklabels, _label = True, True, True
        elif all is not None:
            _ticks, _ticklabels, _label = False, False, False
        else:
            _ticks, _ticklabels, _label = None, None, None

        if ticks is not None:
            _ticks = ticks
        if ticklabels is not None:
            _ticklabels = ticklabels
        if label is not None:
            _label = label

        if _ticks is not None:
            self.major_ticks.set_visible(_ticks)
            self.minor_ticks.set_visible(_ticks)
        if _ticklabels is not None:
            self.major_ticklabels.set_visible(_ticklabels)
            self.minor_ticklabels.set_visible(_ticklabels)
        if _label is not None:
            self.label.set_visible(_label)





def test_axis_artist():
    global axisline

    #self._axislines[loc] = new_fixed_axis(loc=loc, axes=axes)
    from mpl_toolkits.axisartist import AxisArtistHelperRectlinear
    fig = plt.figure(1)
    fig.clf()
    ax=fig.add_subplot(111)
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)

    if 1:

        _helper = AxisArtistHelperRectlinear.Fixed(ax, loc="left")
        axisline = AxisArtist(ax, _helper, offset=None, axis_direction="left")
        ax.add_artist(axisline)
        _helper = AxisArtistHelperRectlinear.Fixed(ax, loc="right")
        axisline = AxisArtist(ax, _helper, offset=None, axis_direction="right")
        ax.add_artist(axisline)

    _helper = AxisArtistHelperRectlinear.Fixed(ax, loc="bottom")
    axisline = AxisArtist(ax, _helper, offset=None, axis_direction="bottom")
    axisline.set_label("TTT")
    #axisline.label.set_visible(False)
    ax.add_artist(axisline)

    #axisline.major_ticklabels.set_axis_direction("bottom")
    axisline.major_ticks.set_tick_out(False)

    ax.set_ylabel("Test")

    axisline.label.set_pad(5)


    plt.draw()

def test_axis_artist2():
    global axisline

    #self._axislines[loc] = new_fixed_axis(loc=loc, axes=axes)
    from mpl_toolkits.axislines import AxisArtistHelperRectlinear
    fig = plt.figure(1)
    fig.clf()
    ax=fig.add_subplot(111)
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)


    _helper = AxisArtistHelperRectlinear.Fixed(ax, loc="bottom")
    axisline = AxisArtist(ax, _helper, offset=None, axis_direction="bottom")
    axisline.set_label("TTT")
    ax.add_artist(axisline)

    #axisline.major_ticklabels.set_axis_direction("bottom")
    axisline.major_ticks.set_tick_out(False)


    ax.set_ylabel("Test")

    plt.draw()

if __name__ == "__main__":
    #test_labelbase()
    #test_ticklabels()
    test_axis_artist()
    #test_axis_artist2()


# DONE
# *. ticks, ticklabels, axislabels
# *. workon axisartist

# TODO