0

Typically, if you want to make a secondary Y-axis, you just use subplots, as shown in Adding a y-axis label to secondary y-axis in matplotlib. Is it possible, however, to make a secondary Y-axis without making a subplot.

For example, if I were making a weight-loss graph over time and wanted one side of the Y-axis to be in kilos and the other side to be in pounds. Take the plot generated from the code below:

# Make list of random weights and sort
weight = np.random.uniform(low=80.0, high=90.0, size=(50,))

# Create dataframe from weight list with index for days
df = pd.DataFrame(data=weight, columns=['weight'])
df = df.sort_values(by=['weight'], ascending=False).reset_index(drop=True)
df = df.reset_index().rename(columns={'index': 'days'})
print(df)
X = df.days
y = df.weight

# Plot outputs
p1 = plt.scatter(X, y, color='black', label='Measured weight')
# Add tick values that automatically adjust to the amount of the points in the weight list
plt.xticks(np.arange(0, df['days'].max() + 2, step=2))
plt.yticks(np.arange(int(df['weight'].min()) - 2, int(df['weight'].max()) + 2, step=1))
# Add labels, title, and legend
plt.ylabel('Weight (kg)')
plt.xlabel('Days on Diet')
plt.title('Weight Over Time')
# Display plot
plt.show()

Is it possible to add a second Y-scale that has pounds without using a subplot?

DrakeMurdoch
  • 765
  • 11
  • 26
  • Similar to [this](https://matplotlib.org/3.1.1/gallery/subplots_axes_and_figures/fahrenheit_celsius_scales.html#sphx-glr-gallery-subplots-axes-and-figures-fahrenheit-celsius-scales-py) perhaps. I don't see why `twinx` won't work here. – BigBen Oct 29 '20 at 16:31
  • Note that you can graph from pandas directly and that might make the creation of the secondary axis easier. – BigBen Oct 29 '20 at 16:37
  • You can also do this w/o a twinned axis... https://matplotlib.org/3.1.0/gallery/subplots_axes_and_figures/secondary_axis.html – Jody Klymak Oct 29 '20 at 16:58

0 Answers0