Thanks to visit codestin.com
Credit goes to github.com

Skip to content

twinx not respecting log-scale #18385

Closed
@MarkusSchwarz1980

Description

@MarkusSchwarz1980

Bug report

Bug summary

When a new Axes is created with twinx() from an Axes that has a logarithmic scale, the resulting Axes does not have the logarithmic scale.

Code for reproduction

This code is based on the matplotlib example Plots with different scales

import numpy as np
import matplotlib.pyplot as plt

# Create some mock data
t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)

fig1, ax1 = plt.subplots(num='1')

color = 'tab:red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.set_xscale('log')  # set x axis to log scale
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('sin', color=color)  # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)

fig1.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

Actual outcome

The second axis does not have logarithmic scaling:
twinx1

Expected outcome
By using ax1.set_xscale('log') I expected that the 'twinned' Axes also has a logarithmic scale:
twinx2

By setting the logarithmic scale individually after the second axis has been created gives the desired result

fig2, ax3 = plt.subplots(num='2')

color = 'tab:red'
ax3.set_xlabel('time (s)')
ax3.set_ylabel('exp', color=color)
ax3.plot(t, data1, color=color)
ax3.tick_params(axis='y', labelcolor=color)

ax4 = ax3.twinx()  # instantiate a second axes that shares the same x-axis

# set log scale for both axis
for ax in [ax3, ax4]:
    ax.set_xscale('log')

color = 'tab:blue'
ax4.set_ylabel('sin', color=color)  # we already handled the x-label with ax3
ax4.plot(t, data2, color=color)
ax4.tick_params(axis='y', labelcolor=color)

fig2.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

Matplotlib version

  • Operating system: macOS 10.15.6
  • Matplotlib version: 3.3.1 (from channel conda-forge)
  • Matplotlib backend (print(matplotlib.get_backend())): Qt5Agg
  • Python version: 3.7.8
  • Jupyter version (if applicable):
  • Other libraries:

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions