Search code examples
matplotlibplotaxes

How do create a scale for a second axis without unnecessary (or redundant) plotting?


I have a plot in which I have already plotted all my data and a "twined" axis, on which I'd like to use another scale, in this case dates. I also have a list of all the dates corresponding to each element of my data, and want to add an a scale for the dates to the twined axis.

For example, I have

ax2 = ax1.twinx()

and lists x_temporal_data, y_day_offsets, y_dates, all of the same length, and have already plotted the relationship between the first two with

ax1.plot(x_temporal_data, y_day_offsets)

and I just want to have a scale on ax2 for the dates in y_dates, since y_day_offsets and y_dates are "synonyms" for the same time information.

Is there a way to do this without "plotting" something I don't need to display (since all my data is already plotted). For example, I can get the dates to appear perfectly on ax2 with

ax2.plot(len(y_dates)*[some_random_out_of_xrange_value], y_dates)

but that seems like a hack: plotting nothing to "calibrate" the second axis.

Is there a better, more idiomatic way of accomplishing this?


Solution

  • Simply set the scale on the second y-axis to your liking with:

    ax2.set_ylim([min(y_dates), max(y_dates)])