Я создал график с двумя осями X - одна главная ось графика и вторая ось 'twiny ()' под ним.Для второй оси я хочу иметь возможность корректировать вертикальные позиции меток xtick с помощью метода set_y (), чтобы лучше разделять метки.Это не работает для меня, но используя тот же код на исходной оси графика, я могу установить эти позиции меток.
пример сюжета
Чего мне не хватает?Кажется, что только исходные позиции меток осей могут быть изменены вторичными осями, которые не могут быть отрегулированы.Есть идеи?
import matplotlib.pyplot as plt
def figToHtmlImg(fig):
from io import BytesIO
import base64
tmpFile = BytesIO()
fig.savefig(tmpFile, format = 'png')
encoded = base64.b64encode(tmpFile.getvalue())
return '<img src="data:image/png;base64,{}">'.format(encoded)
# Data
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [2.4, 3.6, 2.8, 2.9, 2.6, 1.3, 0.7, 2.5, 3.0, 2.1]
labelsX = [ 2, 2.1, 4, 4.1, 6, 6.1, 8, 8.1, 10, 10.1 ]
labels = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' ]
# Create Plot and Axes
fig = plt.figure(figsize = (8, 6), dpi = 200)
ax = plt.subplot(111)
# Write data to plot
ax.plot(x, y, '#ff0000')
plt.xlim(0, 10)
# Adjust the bottom of the plot to give extra room for new X axes
fig.subplots_adjust(bottom = 0.25)
# Create new axes from the original and position it at the bottom.
ax2 = ax.twiny()
ax2.xaxis.set_ticks_position("bottom")
ax2.xaxis.set_label_position("bottom")
ax2.spines["bottom"].set_position(("axes", -0.2))
ax2.set_frame_on(True)
ax2.patch.set_visible(False)
for sp in ax2.spines.itervalues():
sp.set_visible(False)
ax2.spines["bottom"].set_visible(True)
# Set the axes lables.
ax2.set_xticks(labelsX)
ax2.set_xticklabels(labels)
# MAIN X AXIS TICKS - Adjust the tick label positions.
for i, t in enumerate(ax.get_xticklabels()):
t.set_y(i * -0.015) # This moves the labels down on the main axis.
# SECOND X AXIS TICKS - Adjust the tick label positions.
for i, t in enumerate(ax2.get_xticklabels()):
t.set_y(i * -0.015) # <----- DOES NOT WORK. DOES NOTHING
# Alternate attempt at setting label positions...also does NOT work.
#for i, t in enumerate(ax2.xaxis.get_major_ticks()):
# t.label.set_y(i * -0.025) # <----- DOES NOT WORK. DOES NOTHING.
# Open the file for writing.
path = 'test.html'
file = open(path, 'w')
file.write(figToHtmlImg(fig))
file.close()