matplotlib(Python)中的层次轴标记

2024-04-29 18:36:35 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我在看一个nxn网格,在每个轴上都有动物的标签。但我也有兴趣研究动物群体之间的关系。例如,我可能有脊椎动物和无脊椎动物,脊椎动物中我可能有哺乳动物和爬行动物等等。(如果有关系的话,我对相关矩阵特别感兴趣,并且实际上正在通过seaborn使用热图…)

我想在matplotlib中绘制它,但是沿着轴有分层标记。所以用我上面的例子,我会有像狗,猫,马,蜥蜴,鳄鱼等的标签,然后第一组狗通过马将有哺乳动物的标签,第二组蜥蜴,鳄鱼等将有爬行动物,这两个加在一起会有一个更进一步的脊椎动物的标签。。。在

我该怎么做?在


Tags: 网格关系matplotlib标签seaborn感兴趣群体兴趣
1条回答
网友
1楼 · 发布于 2024-04-29 18:36:35

不幸的是,我不知道如何禁用次要刻度:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from mpl_toolkits.axes_grid.parasite_axes import SubplotHost

fig1 = plt.figure()
ax1 = SubplotHost(fig1, 111)
fig1.add_subplot(ax1)

# Some data
x = np.arange(1,6)
y = np.random.random(len(x))

# First X-axis
ax1.plot(x, y)
ax1.set_xticks(x)
ax1.set_xticklabels(['dog', 'cat', 'horse', 'lizard', 'crocodile'])
#ax1.xaxis.set_label_text('First X-axis') # Uncomment to label axis
ax1.yaxis.set_label_text("Sample data")

# Second X-axis
ax2 = ax1.twiny()
offset = 0, -25 # Position of the second axis
new_axisline = ax2.get_grid_helper().new_fixed_axis
ax2.axis["bottom"] = new_axisline(loc="bottom", axes=ax2, offset=offset)
ax2.axis["top"].set_visible(False)

ax2.set_xticks([0.0, 0.6, 1.0])
ax2.xaxis.set_major_formatter(ticker.NullFormatter())
ax2.xaxis.set_minor_locator(ticker.FixedLocator([0.3, 0.8]))
ax2.xaxis.set_minor_formatter(ticker.FixedFormatter(['mammal', 'reptiles']))

# Third X-axis
ax3 = ax1.twiny()
offset = 0, -50
new_axisline = ax3.get_grid_helper().new_fixed_axis
ax3.axis["bottom"] = new_axisline(loc="bottom", axes=ax3, offset=offset)
ax3.axis["top"].set_visible(False)

ax3.set_xticks([0.0, 1.0])
ax3.xaxis.set_major_formatter(ticker.NullFormatter())
ax3.xaxis.set_minor_locator(ticker.FixedLocator([0.5]))
ax3.xaxis.set_minor_formatter(ticker.FixedFormatter(['vertebrates']))

ax1.grid(1)
plt.show()

enter image description here

相关问题 更多 >