0

Good morning,

is it possible in matplotlib to get a secondary xy axis in the same graph? I am not looking for twinx() or twiny().

I have two data sets: x1, y1 and x2, y2, which i both want to plot in the same graph. I would like to plot the first data set in the normal axes: ax1.plot(x1, y1). The second y-axis should be located on the right and the second x-axis should be located on the top.

But how do i set this up?

Kind regards Thomas

blitzoc
  • 11
  • 2

1 Answers1

0

Taken from matplotlib secondary_axis docu:

import matplotlib.pyplot as plt
import numpy as np
import datetime
import matplotlib.dates as mdates
from matplotlib.ticker import AutoMinorLocator

dates = [datetime.datetime(2018, 1, 1) + datetime.timedelta(hours=k * 6)
         for k in range(240)]
temperature = np.random.randn(len(dates)) * 4 + 6.7
fig, ax = plt.subplots(constrained_layout=True)

ax.plot(dates, temperature)
ax.set_ylabel(r'$T\ [^oC]$')
plt.xticks(rotation=70)


def date2yday(x):
    """Convert matplotlib datenum to days since 2018-01-01."""
    y = x - mdates.date2num(datetime.datetime(2018, 1, 1))
    return y


def yday2date(x):
    """Return a matplotlib datenum for *x* days after 2018-01-01."""
    y = x + mdates.date2num(datetime.datetime(2018, 1, 1))
    return y


secax_x = ax.secondary_xaxis('top', functions=(date2yday, yday2date))
secax_x.set_xlabel('yday [2018]')


def celsius_to_fahrenheit(x):
    return x * 1.8 + 32


def fahrenheit_to_celsius(x):
    return (x - 32) / 1.8


secax_y = ax.secondary_yaxis(
    'right', functions=(celsius_to_fahrenheit, fahrenheit_to_celsius))
secax_y.set_ylabel(r'$T\ [^oF]$')


def celsius_to_anomaly(x):
    return (x - np.mean(temperature))


def anomaly_to_celsius(x):
    return (x + np.mean(temperature))


# use of a float for the position:
secax_y2 = ax.secondary_yaxis(
    1.2, functions=(celsius_to_anomaly, anomaly_to_celsius))
secax_y2.set_ylabel(r'$T - \overline{T}\ [^oC]$')


plt.show()

Results in this:

enter image description here

Dragoner
  • 123
  • 1
  • 12
  • thanks for the input. However, secondary_axis uses a relationship between x1 and x2. Basically, the same data is plotted just with some manipulation of the data, which is then plotted on a different scale. However, i was looking for two independent datasets (x1,y1) and (x2,y2) to be plotted in the same graph. As the values for x1 differ strongly with x2, (and likewise for y1 and y2), i need different scales. – blitzoc Aug 05 '22 at 11:46