matplotlib-无法在第二轴上设置xtick标签位置

时间:2018-12-19 04:01:38

标签: python matplotlib label

我创建了一个具有两个X轴的图-该图的一个主轴,在其下的第二个'twiny()'轴。对于第二个轴,我希望能够使用set_y()方法调整xtick标签的垂直位置,以便更好地分离标签。这对我不起作用,但是在绘图的原始轴上使用相同的代码,我可以设置这些标签的位置。

情节示例 example of the plot

我想念什么?似乎只能调整原始轴标签的位置,而无法调整辅助轴。有什么想法吗?

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()

0 个答案:

没有答案