mwshinn / CanD

6 stars 3 forks source link

Function for axis sharing #18

Closed jankaWIS closed 1 year ago

jankaWIS commented 1 year ago
          Will do/done. Thanks.

I have been now playing with the sharing. It has a problem with sharing an axis more than one so chaining the previous won't work. I have made the following workaround:

    if i>0:
        # sharey, take the before last axis and sharey with the last plotted one, cannot share 2 axis
        c.ax(a[i]).sharey(c.ax(a[i-1])) 
        # need to rescale all axis
        c.ax(a[i]).autoscale()

        # remove ticks from shared y axes
        plt.setp(ax.get_yticklabels(), visible=False)
        # remove ylabel
        ax.set_ylabel('')  

and I think it does the job but at the same time, I'm not 100 % sure that it won't break eventually, that the axis will have correct labels/ticks and scale. Could you please check?

Originally posted by @jankaWIS in https://github.com/mwshinn/CanD/issues/13#issuecomment-873577418


Following this issue/discussion that we had, would you be interested in adding this function to CanD? I guess it could be generalised further and also adapted.

def sharey(a, source):
    """
    Takes axis a that we want to share with axis source. `Update correspondingly to the type of the passed arguments.

    Parameters:
    a: str or matplotlib axis, axis that we want to be shared
    source: str or matplotlib axis, axis that will be the source of the scale and labels
    """
    if isinstance(a, str) and isinstance(source, str):
        # sharey, take the first axis and sharey with the last plotted one
        c.ax(a).sharey(c.ax(source))
        # need to rescale all axis        
        c.ax(a).autoscale()
        # remove ticks from shared y axes
        plt.setp(c.ax(a).get_yticklabels(), visible=False)
        # remove ylabel
        c.ax(a).set_ylabel('')
    elif isinstance(a, str) and isinstance(source, str):
        # sharey, take the first axis and sharey with the last plotted one
        a.sharey(source)
        # need to rescale all axis        
        a.autoscale()
        # remove ticks from shared y axes
        plt.setp(a.get_yticklabels(), visible=False)
        # remove ylabel
        a.set_ylabel('')
    else:
        raise TypeError("Only strings or matplotlib axes are allowed types.")
mwshinn commented 1 year ago

I don't think this is a CanD issue: to share axes in matplotlib you have to share all the axes to the same one common axes, not chain them. CanD should not touch matplotlib's axis sharing features.