问题
I'm trying to make a plot with pylab/matplotlib, and I have two different sets of units for the x axis. So what I would like the plot to have is two axis with different ticks, one on the top and one on the bottom. (E.g. one with miles and one with km or so.)
Something like the graph below (but than I would like multiple X axes, but that doesn't really matter.)
Anyone an idea whether this is possible with pylab?
回答1:
This might be a little late but see if something like this would help:
http://matplotlib.sourceforge.net/examples/axes_grid/simple_axisline4.html
回答2:
Adding multiple axes next to the "original" frame, as seen in the example picture, can be achieved by adding additional axes with twinx
and configuring their spines
attribute.
I think this looks quite similar to the example picture:
import matplotlib.pyplot as plt
import numpy as np
# Set font family
plt.rcParams["font.family"] = "monospace"
# Get figure, axis and additional axes
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = ax1.twinx()
ax4 = ax1.twinx()
# Make space on the right for the additional axes
fig.subplots_adjust(right=0.6)
# Move additional axes to free space on the right
ax3.spines["right"].set_position(("axes", 1.2))
ax4.spines["right"].set_position(("axes", 1.4))
# Set axes limits
ax1.set_xlim(0, 7)
ax1.set_ylim(0, 10)
ax2.set_ylim(15, 55)
ax3.set_ylim(200, 600)
ax4.set_ylim(500, 750)
# Add some random example lines
line1, = ax1.plot(np.random.randint(*ax1.get_ylim(), 8), color="black")
line2, = ax2.plot(np.random.randint(*ax2.get_ylim(), 8), color="green")
line3, = ax3.plot(np.random.randint(*ax3.get_ylim(), 8), color="red")
line4, = ax4.plot(np.random.randint(*ax4.get_ylim(), 8), color="blue")
# Set axes colors
ax1.spines["left"].set_color(line1.get_color())
ax2.spines["right"].set_color(line2.get_color())
ax3.spines["right"].set_color(line3.get_color())
ax4.spines["right"].set_color(line4.get_color())
# Set up ticks and grid lines
ax1.minorticks_on()
ax2.minorticks_on()
ax3.minorticks_on()
ax4.minorticks_on()
ax1.tick_params(direction="in", which="both", colors=line1.get_color())
ax2.tick_params(direction="in", which="both", colors=line2.get_color())
ax3.tick_params(direction="in", which="both", colors=line3.get_color())
ax4.tick_params(direction="in", which="both", colors=line4.get_color())
ax1.grid(axis='y', which='major')
plt.show()
来源:https://stackoverflow.com/questions/751567/both-a-top-and-a-bottom-axis-in-pylab-e-g-w-different-units-or-left-and-rig