Skip to content

Get ticklabels back on shared axis #10911

Closed

Description

Bug report

Bug summary

When sharing the axes through plt.subplots(2, sharex=True) the ticklabels on the upper axes are rightfully suppressed. However, in many cases you may still want/need to show them.

Im matplotlib 2.0.2 this was easily possible by turning them visible again. This is not possible any more with matplotlib 2.2.

Code for reproduction

import matplotlib.pyplot as plt

fig, (ax,ax2) = plt.subplots(2, sharex=True)

plt.setp(ax.get_xticklabels(),visible=True)

plt.show()

Actual outcome in matplotlib 2.2.2

image

Expected outcome, actual outcome in matplotlib 2.0.2

I would expect matplotlib not to break the previously working solution of turning the labels visible. The expected outcome would be, as in version 2.0.2 to see the ticklabels on the upper axes.

image

Activity

  1. pharshalp commented on Apr 5, 2018

    @pharshalp
    Contributor

    @ImportanceOfBeingErnest
    For now, I am using the following workaround...
    (figured out after looking at

    # turn off redundant tick labeling
    )

    import matplotlib.pyplot as plt
    
    fig, (ax,ax2) = plt.subplots(2, sharex=True)
    
    ax.xaxis.set_tick_params(which='both', labelbottom=True)
    
    plt.show()
    

    figure_1

  2. modified the milestones: , v2.2.3 on Apr 6, 2018
  3. jklymak commented on Apr 6, 2018

    @jklymak
    Member

    This seems to be kind of a bad regression.... Do we know what caused it?

  4. jklymak commented on Apr 6, 2018

    @jklymak
    Member

    Oooh, git bisect is cool. looks like #8678 ping @QuLogic

  5. ImportanceOfBeingErnest commented on Apr 6, 2018

    @ImportanceOfBeingErnest
    MemberAuthor

    Yep, so the question is

    • Is this considered to be a break in the API? If so, it should probably be reversed.
    • Is there actually any reason to turn the labels off (i.e. remove them) instead of making them invisible? If so it could make sense to keep it like it is and users have to adapt their code.

    The change from individual artist properties to axis tick properties in #8678 may in the long run have led to other problems like #10882 as well. So probably a critical review is needed here and in general I would argue that if tick_params is to be used for most tick parameters, then it should take all of those as arguments, most importantly rotation, horizontalalignment, verticalalignment and rotation_mode.

  6. jklymak commented on Apr 7, 2018

    @jklymak
    Member

    Well, as of #8678 set_tick_params works for those, so if it doesn't work now then something has changed.

  7. ImportanceOfBeingErnest commented on Apr 7, 2018

    @ImportanceOfBeingErnest
    MemberAuthor

    set_tick_params works for some of those. Say we want to have rotated, red ticklabels with horizontal alignment on the shared axes.

    Previously (as of 2.0) we would just set all the properties we want via the setters (looping or using setp)

    import matplotlib.pyplot as plt
    
    fig, (ax,ax2) = plt.subplots(2, sharex=True)
    
    plt.setp(ax.get_xticklabels(), rotation=45, color="r", 
             ha="right", rotation_mode="anchor", visible=True)
    
    plt.show()
    

    This does not work any more as seen above. So apparently the new recommended way to set label properties is to use set_tick_params. That is however only partially possible. So the equivalent of the above and recommended way would be

    import matplotlib.pyplot as plt
    
    fig, (ax,ax2) = plt.subplots(2, sharex=True)
    
    ax.xaxis.set_tick_params(labelbottom=True, rotation=45, labelcolor="r",)
    plt.setp(ax.get_xticklabels(), ha="right", rotation_mode="anchor")
    
    plt.show()
    

    So we need to find out which arguments are supported by set_tick_params (ha and rotation_mode are not) and possibly change their names (color needs to be labelcolor). This does not look like an API change that simplifies things.

  8. efiring commented on Apr 7, 2018

    @efiring
    Member

    I don't think that reverting this is warranted; ax.tick_params is a nicer interface, and it provides an adequate replacement for the set_visible manipulation. It handles 'labelsize', 'labelrotation', and 'labelcolor' but I don't see the alignments or rotation_mode. It looks like adding them would be a good idea.

    @jklymak, how did you find the alignments etc. to work?

    Here's the full list that ax.tickparams claims to be able to handle, based on a traceback:
    ['size', 'width', 'color', 'tickdir', 'pad', 'labelsize', 'labelcolor', 'zorder', 'gridOn', 'tick1On', 'tick2On', 'label1On', 'label2On', 'length', 'direction', 'left', 'bottom', 'right', 'top', 'labelleft', 'labelbottom', 'labelright', 'labeltop', 'labelrotation', 'grid_agg_filter', 'grid_alpha', 'grid_animated', 'grid_antialiased', 'grid_clip_box', 'grid_clip_on', 'grid_clip_path', 'grid_color', 'grid_contains', 'grid_dash_capstyle', 'grid_dash_joinstyle', 'grid_dashes', 'grid_drawstyle', 'grid_figure', 'grid_fillstyle', 'grid_gid', 'grid_label', 'grid_linestyle', 'grid_linewidth', 'grid_marker', 'grid_markeredgecolor', 'grid_markeredgewidth', 'grid_markerfacecolor', 'grid_markerfacecoloralt', 'grid_markersize', 'grid_markevery', 'grid_path_effects', 'grid_picker', 'grid_pickradius', 'grid_rasterized', 'grid_sketch_params', 'grid_snap', 'grid_solid_capstyle', 'grid_solid_joinstyle', 'grid_transform', 'grid_url', 'grid_visible', 'grid_xdata', 'grid_ydata', 'grid_zorder', 'grid_ms', 'grid_aa', 'grid_ls', 'grid_mec', 'grid_mew', 'grid_mfc', 'grid_lw', 'grid_mfcalt', 'grid_c']

  9. ImportanceOfBeingErnest commented on Apr 7, 2018

    @ImportanceOfBeingErnest
    MemberAuthor

    I'm not decided here. On the one hand it is for sure useful to add horizontalalignment, verticalalignment and rotation_mode.
    But then why not add alpha, fontweight, zorder, style, backgroundcolor etc.?

    The problem is that this interface is already completely cluttered with arguments (which sometimes are not named consistently). This is because it essentially provides access to 3 different things: the tickmarkers, the grid and the labels.
    So for consistency it could take all Text arguments, prepended by label, but that would lead to labelhorizontalalignment and such.
    Further, the code inside set_tick_params is really heavy with a lot of if and dictionary shuffling.
    All this stands opposed to a very clear artist based getter/setter structure, where the only drawback is that you need a loop or a pyplot function (setp) to access it. Providing setp as axes method is really all that is needed here.

    Concerning the visibility, it's not really clear why some new mechanism is needed. Why is the visible property of the text not the one we want to use?

  10. efiring commented on Apr 7, 2018

    @efiring
    Member

    You make good points here; but I think that neither the setp interface nor the Axes.tick_params interface is ideal. I added the latter quite some time ago as a one-stop-shop for common customizations, accessible from the Axes level. For example, using the 'colors' kwarg one can change the color of the ticks and their labels, for x and/or y, major and/or minor. The grid parameters were added later. It might or might not be wise, but I don't think it is essential that every possible property be controllable from this interface, but it makes sense to provide control over those for reasonably common use cases, possibly with additional aggregations to suit real-life uses.

    Regarding visible: why draw something, time after time, if it is always going to be invisible? The boolean flags for whether to generate ticks and labels on top or bottom, etc., are not new at all, and have long been used internally. Logically, it makes more sense to turn a set of ticks on or off than to make each one visible or invisible. Longer term, we really want to revamp the tick system to use collections instead of always working with expanding and contracting lists of complex Tick objects.

  11. ImportanceOfBeingErnest commented on Apr 7, 2018

    @ImportanceOfBeingErnest
    MemberAuthor

    So I guess the test

    is now testing if an empty list is really empty?

  12. ImportanceOfBeingErnest commented on Apr 7, 2018

    @ImportanceOfBeingErnest
    MemberAuthor

    When using shared axes, the solution is to use set_tick_params to get the labels back

    import matplotlib.pyplot as plt
    
    fig, ((ax,ax2),(ax3,ax4)) = plt.subplots(2,2, sharex=True, sharey=True)
    
    ax.xaxis.set_tick_params(labelbottom=True, labelcolor="r")
    
    plt.show()
    

    When using unshared axes, the solution is to turn them visible:

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(2,2)
    for ax in axes.flat:
        ax.label_outer()
    
    plt.setp(axes[0,0].get_xticklabels(),visible=True, color="r")
    
    plt.show()
    

    Both codes give the same plot

    image

    Confusing stuff.

  13. jklymak commented on Apr 7, 2018

    @jklymak
    Member

    That’s gotta be because of whatever label_outer does. I’d never even heard of that method.

  14. ImportanceOfBeingErnest commented on Apr 7, 2018

    @ImportanceOfBeingErnest
    MemberAuthor

    Guess what, label_outer() turns the labels of internal axes invisible. 😂

    for label in self.get_xticklabels(which="both"):
    label.set_visible(False)

    Anyways, I have created a PR #10981 to at least document the changes that have been introduced via #8678.

  15. efiring commented on Apr 7, 2018

    @efiring
    Member

    Right, label_outer should be updated to use tick_params instead of set_visible. This looks like an oversight. label_outer has been around for a long time, but I've never used it and wasn't aware of it.

  16. akiross commented on May 10, 2018

    @akiross

    I know this is not directly involving matplotlib, but I noticed that with pandas, tick_params and set_tick_params do not solve the issue.

    Here's an example code: when has_bug is set to True, axes are still not added. Using matplotlib 2.2.2 and pandas 0.22.0.

    import numpy as np
    import pandas as pd
    from matplotlib import pyplot as plt
    
    has_bug = True
    
    fig, axes = plt.subplots(2, figsize=(3, 3), sharex=True)
    axes = axes.flatten()
    for i in range(2):
        if has_bug:
            pd.Series(data=np.random.random(10)).plot(ax=axes[i])
        else:
            axes[i].plot(np.random.random(10))
        axes[i].set_title(f'Foo {i}')
        axes[i].tick_params(labelbottom=True)
        
    fig.suptitle('Foobar')
    fig.savefig('test.png')
    

    Plotting with pandas

    broken

    Plotting with mpl

    working

    EDIT: I tried with setp, tick_params and set_tick_params.

  17. ImportanceOfBeingErnest commented on May 10, 2018

    @ImportanceOfBeingErnest
    MemberAuthor

    Mhh, I can reproduce this with matplotlib 2.2.2.
    However, on current master with pandas 0.22.0 I do get the desired outcome in both cases. So in that sense, it is involving matplotlib, but apparently is working fine in the development version.

    As for a workaround, you may still set the ticks visible after the loop.

    plt.setp(axes[0].get_xticklabels(), visible=True)
    
  18. tdgunes commented on Feb 5, 2019

    @tdgunes

    Also, I can reproduce this with 2.2.3. I used this workaround that is mentioned above:

    ax.yaxis.set_tick_params(which='both', labelbottom=True)
  19. shijiegu commented on May 29, 2024

    @shijiegu

    Hi! The workaround above ax.xaxis.set_tick_params(which='both', labelbottom=True) does not work if different subplots need different labels.
    Imagine each subplot shows data from one subject undergoing a treatment. Across subjects, we align x axis origin on treatment day 0, but I would also like the actual dates (which differ by subjects) at the bottom of the ticks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions