Repository: SciTools/cartopy

Issue:
Incorrect tick labels
When putting tick labels on a `cartopy.crs.PlateCarree` projection the longitude labels are incorrect if a central longitude of 180 is used. To reproduce:

```
# labels are incorrect
plt.figure()
ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180))
ax.coastlines(zorder=1)
xticks = range(0, 361, 60)
ax.set_xticks(xticks, crs=ccrs.PlateCarree())
yticks = range(-90, 91, 30)
ax.set_yticks(yticks, crs=ccrs.PlateCarree())
ax.set_title('central longitude = 180')
```

![180](https://f.cloud.github.com/assets/390602/135002/d18f1294-7107-11e2-90ef-454394da0a93.png)

(I also just realised 90S and 90N are missing on the latitude axis too!)

If I use 0 as the central longitude then the longitude labels are correct.

```
# works fine (as long as longitudes in the range [-180, 180])
plt.figure()
ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=0))
ax.coastlines(zorder=1)
xticks = range(-180, 181, 60)
ax.set_xticks(xticks, crs=ccrs.PlateCarree())
yticks = range(-90, 91, 30)
ax.set_yticks(yticks, crs=ccrs.PlateCarree())
ax.set_title('central longitude = 0')
```

![0](https://f.cloud.github.com/assets/390602/135003/d599bc5e-7107-11e2-8dfe-532e0701eb1e.png)

Perhaps I'm just doing this wrong?



Discussion:
There was a pull request merged 2 days ago which adds proper support for tick (in some very limited projections). The ticks you're seeing here are simple matplotlib ticks which have no knowledge of cartopy - hence they are plotting in the "native" coordinate system.

Would you be willing to give the functionality added by @pp-mo in #200 a shot?

OK you mean using the `ax.gridlines()` method? I did this:

```
plt.figure()
ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180))
ax.coastlines(zorder=1)
ax.gridlines(draw_labels=True)
ax.set_title('ax.gridlines(draw_labels=True)')
```

which produces:

![gridlines](https://f.cloud.github.com/assets/390602/135550/fd18189a-7128-11e2-9528-6e3e11a95ea9.png)

which is obviously not quite right! I guess I have misunderstood. I thought because `GeoAxes` has its own `set_xticks` method that accepts a crs that it would handle things correctly? Anyway, what I would like to be able to do is label the left and bottom axes, and show only ticks, not grid lines. Is that possible?

> which is obviously not quite right!

Agreed! :smile: 

> I thought because GeoAxes has its own set_xticks method that accepts a crs that it would handle things correctly?

We've not yet done anything to the `set_xticks` family of methods which will mean the CRS is handled appropriately (should it always be in lat long?)

> Anyway, what I would like to be able to do is label the left and bottom axes, and show only ticks, not grid lines. Is that possible?

In truth, we've not focused on this so much. Your original approach might actually be easier in the short term - I'd think about defining a Formatter which takes the native coordinates and transforms them into the coordinate system you wanted. As for the `+/- 90` not showing up, I'm pretty sure there is nothing special going on and that the clipping is part of the standard (though difficult to track down) matplotlib behaviour. If you want to talk about this over a mailing list, you can open a thread on the matplotlib-devel and prefix the subject with `cartopy:` to see if there are other who can help out with the clipping problem.

Cheers,

OK well I combined this with `ax.set_xticklabels` to get what I wanted in a hacky way. The `+/- 90` was weird because it only happens when I used `PlateCarree(central_longitude=180)` but not when I used `PlateCarree()`... That is partly why I thought there may be a bug in here somewhere...

The mouse-over positions are also reported incorrectly with `central_longitude=180`.

> The mouse-over positions are also reported incorrectly with central_longitude=180.

@bblay - I can't reproduce this. Are you doing something like:

```
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180))
ax.coastlines()
plt.show()
```

> Are you doing something like:

Yep, I cut and paste that into python and when I hover the mouse near the left edge it says -178.

I just noticed it also has the correct coords, with units, in brackets afterwards
so this is probably a feature, not a bug.

There are still issues with tick marks/gridlines that need to be addressed, but perhaps this particular issue can be closed now and replaced with more specific issues/feature requests?

> Yep, I cut and paste that into python and when I hover the mouse near the left edge it says -178.

Those coordinates are the coordinates of the projection you are plotting (which in your case are shifted by 180 degrees. The coordinates in brackets are the coordinates in "lons and lats" which are probably what you're expecting. Thanks for following this through @bblay.

> There are still issues with tick marks/gridlines that need to be addressed, but perhaps this particular issue can be closed now and replaced with more specific issues/feature requests?

I don't want to loose any bug report. I'm pretty certain the repeated 180/-180 exists in the tick marks, is there anything else that I'm missing? I agree we can go ahead and open a specific issue for this (would you mind doing this?). When you're happy that all the issues are covered by folllow-up issues, please go ahead and close this one.

Cheers @ajdawson & @bblay .


Resolving patch:
diff --git a/lib/cartopy/examples/tick_labels.py b/lib/cartopy/examples/tick_labels.py
new file mode 100644
--- /dev/null
+++ b/lib/cartopy/examples/tick_labels.py
@@ -0,0 +1,45 @@
+__tags__ = ['Miscellanea']
+"""
+This example demonstrates adding tick labels to maps on rectangular
+projections using special tick formatters.
+
+"""
+import cartopy.crs as ccrs
+from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
+import matplotlib.pyplot as plt
+
+
+def main():
+    plt.figure(figsize=(8, 10))
+
+    # Label axes of a Plate Carree projection with a central longitude of 180:
+    ax1 = plt.subplot(211, projection=ccrs.PlateCarree(central_longitude=180))
+    ax1.set_global()
+    ax1.coastlines()
+    ax1.set_xticks([0, 60, 120, 180, 240, 300, 360], crs=ccrs.PlateCarree())
+    ax1.set_yticks([-90, -60, -30, 0, 30, 60, 90], crs=ccrs.PlateCarree())
+    lon_formatter = LongitudeFormatter(zero_direction_label=True)
+    lat_formatter = LatitudeFormatter()
+    ax1.xaxis.set_major_formatter(lon_formatter)
+    ax1.yaxis.set_major_formatter(lat_formatter)
+
+    # Label axes of a Mercator projection without degree symbols in the labels
+    # and formatting labels to include 1 decimal place:
+    ax2 = plt.subplot(212, projection=ccrs.Mercator())
+    ax2.set_global()
+    ax2.coastlines()
+    ax2.set_xticks([-180, -120, -60, 0, 60, 120, 180], crs=ccrs.PlateCarree())
+    ax2.set_yticks([-78.5, -60, -25.5, 25.5, 60, 80], crs=ccrs.PlateCarree())
+    lon_formatter = LongitudeFormatter(number_format='.1f',
+                                       degree_symbol='',
+                                       dateline_direction_label=True)
+    lat_formatter = LatitudeFormatter(number_format='.1f',
+                                      degree_symbol='')
+    ax2.xaxis.set_major_formatter(lon_formatter)
+    ax2.yaxis.set_major_formatter(lat_formatter)
+
+    plt.show()
+
+
+if __name__ == '__main__':
+    main()
diff --git a/lib/cartopy/mpl/ticker.py b/lib/cartopy/mpl/ticker.py
new file mode 100644
--- /dev/null
+++ b/lib/cartopy/mpl/ticker.py
@@ -0,0 +1,266 @@
+# (C) British Crown Copyright 2014, Met Office
+#
+# This file is part of cartopy.
+#
+# cartopy is free software: you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the
+# Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# cartopy is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with cartopy.  If not, see <http://www.gnu.org/licenses/>.
+"""This module contains tools for handling tick marks in cartopy."""
+from matplotlib.ticker import Formatter
+
+import cartopy.crs as ccrs
+from cartopy.mpl.geoaxes import GeoAxes
+
+
+class _PlateCarreeFormatter(Formatter):
+    """
+    Base class for formatting ticks on geographical axes using a
+    rectangular projection (e.g. Plate Carree, Mercator).
+
+    """
+
+    _target_projection = ccrs.PlateCarree()
+
+    def __init__(self, degree_symbol=u'\u00B0', number_format='g',
+                 transform_precision=1e-8):
+        """
+        Base class for simpler implementation of specialised formatters
+        for latitude and longitude axes.
+
+        """
+        self._degree_symbol = degree_symbol
+        self._number_format = number_format
+        self._transform_precision = transform_precision
+
+    def __call__(self, value, pos=None):
+        if not isinstance(self.axis.axes, GeoAxes):
+            raise TypeError("This formatter can only be "
+                            "used with cartopy axes.")
+        # We want to produce labels for values in the familiar Plate Carree
+        # projection, so convert the tick values from their own projection
+        # before formatting them.
+        source = self.axis.axes.projection
+        if not isinstance(source, (ccrs._RectangularProjection,
+                                   ccrs.Mercator)):
+            raise TypeError("This formatter cannot be used with "
+                            "non-rectangular projections.")
+        projected_value = self._apply_transform(value, self._target_projection,
+                                                source)
+        # Round the transformed value using a given precision for display
+        # purposes. Transforms can introduce minor rounding errors that make
+        # the tick values look bad, these need to be accounted for.
+        f = 1. / self._transform_precision
+        projected_value = round(f * projected_value) / f
+        # Return the formatted values, the formatter has both the re-projected
+        # tick value and the original axis value available to it.
+        return self._format_value(projected_value, value)
+
+    def _format_value(self, value, original_value):
+        hemisphere = self._hemisphere(value, original_value)
+        fmt_string = u'{value:{number_format}}{degree}{hemisphere}'
+        return fmt_string.format(value=abs(value),
+                                 number_format=self._number_format,
+                                 degree=self._degree_symbol,
+                                 hemisphere=hemisphere)
+
+    def _apply_transform(self, value, target_proj, source_crs):
+        """
+        Given a single value, a target projection and a source CRS,
+        transforms the value from the source CRS to the target
+        projection, returning a single value.
+
+        """
+        raise NotImplementedError("A subclass must implement this method.")
+
+    def _hemisphere(self, value, value_source_crs):
+        """
+        Given both a tick value in the Plate Carree projection and the
+        same value in the source CRS returns a string indicating the
+        hemisphere that the value is in.
+
+        Must be over-ridden by the derived class.
+
+        """
+        raise NotImplementedError("A subclass must implement this method.")
+
+
+class LatitudeFormatter(_PlateCarreeFormatter):
+    """Tick formatter for latitude axes."""
+    def __init__(self, degree_symbol=u'\u00B0', number_format='g',
+                 transform_precision=1e-8):
+        """
+        Tick formatter for a latitude axis.
+
+        The axis must be part of an axes defined on a rectangular
+        projection (e.g. Plate Carree, Mercator).
+
+        .. note::
+
+           A formatter can only be used for one axis. A new formatter
+           must be created for every axis that needs formatted labels.
+
+        Kwargs:
+
+        * degree_symbol (string):
+            The character(s) used to represent the degree symbol in the
+            tick labels. Defaults to u'\u00B0' which is the unicode
+            degree symbol. Can be an empty string if no degree symbol is
+            desired.
+
+        * number_format (string):
+            Format string to represent the tick values. Defaults to 'g'.
+
+        * transform_precision (float):
+            Sets the precision (in degrees) to which transformed tick
+            values are rounded. The default is 1e-7, and should be
+            suitable for most use cases. To control the appearance of
+            tick labels use the *number_format* keyword.
+
+        Examples:
+
+        Label latitudes from -90 to 90 on a Plate Carree projection::
+
+            ax = plt.axes(projection=PlateCarree())
+            ax.set_global()
+            ax.set_yticks([-90, -60, -30, 0, 30, 60, 90],
+                          crs=ccrs.PlateCarree())
+            lat_formatter = LatitudeFormatter()
+            ax.yaxis.set_major_formatter(lat_formatter)
+
+        Label latitudes from -80 to 80 on a Mercator projection, this
+        time omitting the degree symbol::
+
+            ax = plt.axes(projection=Mercator())
+            ax.set_global()
+            ax.set_yticks([-90, -60, -30, 0, 30, 60, 90],
+                          crs=ccrs.PlateCarree())
+            lat_formatter = LatitudeFormatter(degree_symbol='')
+            ax.yaxis.set_major_formatter(lat_formatter)
+
+        """
+        super(LatitudeFormatter, self).__init__(
+            degree_symbol=degree_symbol,
+            number_format=number_format,
+            transform_precision=transform_precision)
+
+    def _apply_transform(self, value, target_proj, source_crs):
+        return target_proj.transform_point(0, value, source_crs)[1]
+
+    def _hemisphere(self, value, value_source_crs):
+        if value > 0:
+            hemisphere = 'N'
+        elif value < 0:
+            hemisphere = 'S'
+        else:
+            hemisphere = ''
+        return hemisphere
+
+
+class LongitudeFormatter(_PlateCarreeFormatter):
+    """Tick formatter for a longitude axis."""
+
+    def __init__(self,
+                 zero_direction_label=False,
+                 dateline_direction_label=False,
+                 degree_symbol=u'\u00B0',
+                 number_format='g',
+                 transform_precision=1e-8):
+        """
+        Create a formatter for longitude values.
+
+        The axis must be part of an axes defined on a rectangular
+        projection (e.g. Plate Carree, Mercator).
+
+        .. note::
+
+           A formatter can only be used for one axis. A new formatter
+           must be created for every axis that needs formatted labels.
+
+        Kwargs:
+
+        * zero_direction_label (False | True):
+            If *True* a direction label (E or W) will be drawn next to
+            longitude labels with the value 0. If *False* then these
+            labels will not be drawn. Defaults to *False* (no direction
+            labels).
+
+        * dateline_direction_label (False | True):
+            If *True* a direction label (E or W) will be drawn next to
+            longitude labels with the value 180. If *False* then these
+            labels will not be drawn. Defaults to *False* (no direction
+            labels).
+
+        * degree_symbol (string):
+            The symbol used to represent degrees. Defaults to u'\u00B0'
+            which is the unicode degree symbol.
+
+        * number_format (string):
+            Format string to represent the longitude values. Defaults to
+            'g'.
+
+        * transform_precision (float):
+            Sets the precision (in degrees) to which transformed tick
+            values are rounded. The default is 1e-7, and should be
+            suitable for most use cases. To control the appearance of
+            tick labels use the *number_format* keyword.
+
+        Examples:
+
+        Label longitudes from -180 to 180 on a Plate Carree projection
+        with a central longitude of 0::
+
+            ax = plt.axes(projection=PlateCarree())
+            ax.set_global()
+            ax.set_xticks([-180, -120, -60, 0, 60, 120, 180],
+                          crs=ccrs.PlateCarree())
+            lon_formatter = LongitudeFormatter()
+            ax.xaxis.set_major_formatter(lon_formatter)
+
+        Label longitudes from 0 to 360 on a Plate Carree projection
+        with a central longitude of 180::
+
+            ax = plt.axes(projection=PlateCarree(central_longitude=180))
+            ax.set_global()
+            ax.set_xticks([0, 60, 120, 180, 240, 300, 360],
+                          crs=ccrs.PlateCarree())
+            ont_formatter = LongitudeFormatter()
+            ax.xaxis.set_major_formatter(lon_formatter)
+
+        """
+        super(LongitudeFormatter, self).__init__(
+            degree_symbol=degree_symbol,
+            number_format=number_format,
+            transform_precision=transform_precision)
+        self._zero_direction_labels = zero_direction_label
+        self._dateline_direction_labels = dateline_direction_label
+
+    def _apply_transform(self, value, target_proj, source_crs):
+        return target_proj.transform_point(value, 0, source_crs)[0]
+
+    def _hemisphere(self, value, value_source_crs):
+        # Perform basic hemisphere detection.
+        if value < 0:
+            hemisphere = 'W'
+        elif value > 0:
+            hemisphere = 'E'
+        else:
+            hemisphere = ''
+        # Correct for user preferences:
+        if value == 0 and self._zero_direction_labels:
+            # Use the original tick value to determine the hemisphere.
+            if value_source_crs < 0:
+                hemisphere = 'E'
+            else:
+                hemisphere = 'W'
+        if value in (-180, 180) and not self._dateline_direction_labels:
+            hemisphere = ''
+        return hemisphere


Test patch:
diff --git a/lib/cartopy/tests/mpl/test_ticker.py b/lib/cartopy/tests/mpl/test_ticker.py
new file mode 100644
--- /dev/null
+++ b/lib/cartopy/tests/mpl/test_ticker.py
@@ -0,0 +1,206 @@
+# (C) British Crown Copyright 2014, Met Office
+#
+# This file is part of cartopy.
+#
+# cartopy is free software: you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the
+# Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# cartopy is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with cartopy.  If not, see <http://www.gnu.org/licenses/>.
+from mock import Mock
+from nose.tools import assert_equal, assert_raises_regexp
+from matplotlib.axes import Axes
+
+import cartopy.crs as ccrs
+from cartopy.mpl.geoaxes import GeoAxes
+from cartopy.mpl.ticker import LatitudeFormatter, LongitudeFormatter
+
+
+def test_LatitudeFormatter_bad_axes():
+    formatter = LatitudeFormatter()
+    formatter.axis = Mock(axes=Mock(Axes, projection=ccrs.PlateCarree()))
+    message = 'This formatter can only be used with cartopy axes.'
+    with assert_raises_regexp(TypeError, message):
+        formatter(0)
+
+
+def test_LatitudeFormatter_bad_projection():
+    formatter = LatitudeFormatter()
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=ccrs.Orthographic()))
+    message = 'This formatter cannot be used with non-rectangular projections.'
+    with assert_raises_regexp(TypeError, message):
+        formatter(0)
+
+
+def test_LongitudeFormatter_bad_axes():
+    formatter = LongitudeFormatter()
+    formatter.axis = Mock(axes=Mock(Axes, projection=ccrs.PlateCarree()))
+    message = 'This formatter can only be used with cartopy axes.'
+    with assert_raises_regexp(TypeError, message):
+        formatter(0)
+
+
+def test_LongitudeFormatter_bad_projection():
+    formatter = LongitudeFormatter()
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=ccrs.Orthographic()))
+    message = 'This formatter cannot be used with non-rectangular projections.'
+    with assert_raises_regexp(TypeError, message):
+        formatter(0)
+
+
+def test_LatitudeFormatter():
+    formatter = LatitudeFormatter()
+    p = ccrs.PlateCarree()
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-90, -60, -30, 0, 30, 60, 90]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'90\u00B0S', u'60\u00B0S', u'30\u00B0S', u'0\u00B0',
+                u'30\u00B0N', u'60\u00B0N', u'90\u00B0N']
+    assert_equal(result, expected)
+
+
+def test_LatitudeFormatter_degree_symbol():
+    formatter = LatitudeFormatter(degree_symbol='')
+    p = ccrs.PlateCarree()
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-90, -60, -30, 0, 30, 60, 90]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'90S', u'60S', u'30S', u'0',
+                u'30N', u'60N', u'90N']
+    assert_equal(result, expected)
+
+
+def test_LatitudeFormatter_number_format():
+    formatter = LatitudeFormatter(number_format='.2f')
+    p = ccrs.PlateCarree()
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-90, -60, -30, 0, 30, 60, 90]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'90.00\u00B0S', u'60.00\u00B0S', u'30.00\u00B0S',
+                u'0.00\u00B0', u'30.00\u00B0N', u'60.00\u00B0N',
+                u'90.00\u00B0N']
+    assert_equal(result, expected)
+
+
+def test_LatitudeFormatter_mercator():
+    formatter = LatitudeFormatter()
+    p = ccrs.Mercator()
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-15496570.739707904, -8362698.548496634,
+                  -3482189.085407435, 0.0, 3482189.085407435,
+                  8362698.548496634, 15496570.739707898]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'80\u00B0S', u'60\u00B0S', u'30\u00B0S', u'0\u00B0',
+                u'30\u00B0N', u'60\u00B0N', u'80\u00B0N']
+    assert_equal(result, expected)
+
+
+def test_LatitudeFormatter_small_numbers():
+    formatter = LatitudeFormatter(number_format='.7f')
+    p = ccrs.PlateCarree()
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [40.1275150, 40.1275152, 40.1275154]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'40.1275150\u00B0N', u'40.1275152\u00B0N',
+                u'40.1275154\u00B0N']
+    assert_equal(result, expected)
+
+
+def test_LongitudeFormatter_central_longitude_0():
+    formatter = LongitudeFormatter(dateline_direction_label=True)
+    p = ccrs.PlateCarree()
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-180, -120, -60, 0, 60, 120, 180]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'180\u00B0W', u'120\u00B0W', u'60\u00B0W', u'0\u00B0',
+                u'60\u00B0E', u'120\u00B0E', u'180\u00B0E']
+    assert_equal(result, expected)
+
+
+def test_LongitudeFormatter_central_longitude_180():
+    formatter = LongitudeFormatter(zero_direction_label=True)
+    p = ccrs.PlateCarree(central_longitude=180)
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-180, -120, -60, 0, 60, 120, 180]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'0\u00B0E', u'60\u00B0E', u'120\u00B0E', u'180\u00B0',
+                u'120\u00B0W', u'60\u00B0W', u'0\u00B0W']
+    assert_equal(result, expected)
+
+
+def test_LongitudeFormatter_central_longitude_120():
+    formatter = LongitudeFormatter()
+    p = ccrs.PlateCarree(central_longitude=120)
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-180, -120, -60, 0, 60, 120, 180]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'60\u00B0W', u'0\u00B0', u'60\u00B0E', u'120\u00B0E',
+                u'180\u00B0', u'120\u00B0W', u'60\u00B0W']
+    assert_equal(result, expected)
+
+
+def test_LongitudeFormatter_degree_symbol():
+    formatter = LongitudeFormatter(degree_symbol='',
+                                   dateline_direction_label=True)
+    p = ccrs.PlateCarree()
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-180, -120, -60, 0, 60, 120, 180]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'180W', u'120W', u'60W', u'0', u'60E', u'120E', u'180E']
+    assert_equal(result, expected)
+
+
+def test_LongitudeFormatter_number_format():
+    formatter = LongitudeFormatter(number_format='.2f',
+                                   dateline_direction_label=True)
+    p = ccrs.PlateCarree()
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-180, -120, -60, 0, 60, 120, 180]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'180.00\u00B0W', u'120.00\u00B0W', u'60.00\u00B0W',
+                u'0.00\u00B0', u'60.00\u00B0E', u'120.00\u00B0E',
+                u'180.00\u00B0E']
+    assert_equal(result, expected)
+
+
+def test_LongitudeFormatter_mercator():
+    formatter = LongitudeFormatter(dateline_direction_label=True)
+    p = ccrs.Mercator()
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-20037508.342783064, -13358338.895188706,
+                  -6679169.447594353, 0.0, 6679169.447594353,
+                  13358338.895188706, 20037508.342783064]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'180\u00B0W', u'120\u00B0W', u'60\u00B0W', u'0\u00B0',
+                u'60\u00B0E', u'120\u00B0E', u'180\u00B0E']
+    assert_equal(result, expected)
+
+
+def test_LongitudeFormatter_small_numbers_0():
+    formatter = LongitudeFormatter(number_format='.7f')
+    p = ccrs.PlateCarree(central_longitude=0)
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-17.1142343, -17.1142340, -17.1142337]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'17.1142343\u00B0W', u'17.1142340\u00B0W',
+                u'17.1142337\u00B0W']
+    assert_equal(result, expected)
+
+
+def test_LongitudeFormatter_small_numbers_180():
+    formatter = LongitudeFormatter(zero_direction_label=True,
+                                   number_format='.7f')
+    p = ccrs.PlateCarree(central_longitude=180)
+    formatter.axis = Mock(axes=Mock(GeoAxes, projection=p))
+    test_ticks = [-17.1142343, -17.1142340, -17.1142337]
+    result = [formatter(tick) for tick in test_ticks]
+    expected = [u'162.8857657\u00B0E', u'162.8857660\u00B0E',
+                u'162.8857663\u00B0E']
+    assert_equal(result, expected)