0

I am able to produce the attached plot with two axes with this code:

import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

x = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.65]
y = [0, 0.15, 0.3, 0.35, 0.4, 0.55, 0.57, 0.58]

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
def func(x, pos):
    return str(2*x)
formatter = FuncFormatter(func)
ax2.xaxis.set_major_formatter(formatter)
ax1.set_ylim([0,1])
ax1.grid(b=True, which='major', color='k', linestyle='--')
ax1.plot(x, y)
plt.savefig('test.png')

But how do I make the upper x-axis range run from 0 to 1.4? I don't know the x range in advance, so 1.4 is a magic number that should not be used. I am happy to be pointed to a tutorial that explains this or a duplicate answer. I can't find either.

enter image description here

I have a solution to the problem, but it's a hack:

ax2.set_xlim([0,0.7])

enter image description here

tommy.carstensen
  • 8,962
  • 15
  • 65
  • 108

1 Answers1

1

What's the main goal with including the relabeling of the ticks?

def func(x, pos):
    return str(2*x)
formatter = FuncFormatter(func)
ax2.xaxis.set_major_formatter(formatter)

It seems like omitting it will give you the right answer:

import matplotlib.pyplot as plt

x = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.65]
y = [0, 0.15, 0.3, 0.35, 0.4, 0.55, 0.57, 0.58]

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
ax1.set_ylim([0,1])
ax1.grid(b=True, which='major', color='k', linestyle='--')
ax1.plot(x, y)
ax2.set_xlim(0,2*ax1.get_xlim()[1])
plt.show()
tommy.carstensen
  • 8,962
  • 15
  • 65
  • 108
Ben
  • 6,986
  • 6
  • 44
  • 71