Python matplotlib matshow xtick顶部和底部的标签

Python matplotlib matshow xtick顶部和底部的标签,python,matplotlib,Python,Matplotlib,我正试图想象一个名称共现矩阵。这个版本可以正常工作: 将熊猫作为pd导入 将numpy作为np导入 导入字符串 将matplotlib.pyplot作为plt导入 n=10 名称=['Long Name'+字符串中后缀的后缀。ascii_大写[:n]] df=pd.DataFrame(np.random.randint(01000,size=(n,n)), 列=名称,索引=名称) 图=plt.图() ax=plt.gca() im=ax.matshow(df,interpolation='non

我正试图想象一个名称共现矩阵。这个版本可以正常工作:

将熊猫作为pd导入
将numpy作为np导入
导入字符串
将matplotlib.pyplot作为plt导入
n=10
名称=['Long Name'+字符串中后缀的后缀。ascii_大写[:n]]
df=pd.DataFrame(np.random.randint(01000,size=(n,n)),
列=名称,索引=名称)
图=plt.图()
ax=plt.gca()
im=ax.matshow(df,interpolation='none')
图颜色条(im)
ax.set_xticks(np.arange(n))
ax.setxticklabels(名称)
ax.集合点(np.arange(n))
ax.设置标签(名称)
ax.xaxis.set_ticks_位置(“底部”)
plt.setp(ax.getxticklabels(),旋转=45,
ha=“右”,旋转模式=“锚定”)
对于(i,j),在np.ndenumerate(df)中的z:
如果z!=0:
ax.text(j,i,str(z),ha=“中心”,va=“中心”)
ax.集合标题(“名称共现”)
图1紧_布局图()
plt.show()
问题是我的实际矩阵相当大,所以我想在顶部和底部都显示名称。我尝试使用twiny来实现这一点:

将熊猫作为pd导入
将numpy作为np导入
导入字符串
将matplotlib.pyplot作为plt导入
n=10
名称=['Long Name'+字符串中后缀的后缀。ascii_大写[:n]]
df=pd.DataFrame(np.random.randint(01000,size=(n,n)),
列=名称,索引=名称)
图=plt.图()
botax=plt.gca()
im=botax.matshow(df,interpolation='none')
图颜色条(im)
topax=botax.twiny()
对于拉链中的ax、ha、pos([topax、botax]、“左”、“右”]、[“上”、“下”]):
ax.set_xticks(np.arange(n))
ax.setxticklabels(名称)
ax.集合点(np.arange(n))
ax.设置标签(名称)
ax.xaxis.set_ticks_位置(位置)
plt.setp(ax.getxticklabels(),旋转=45,
ha=ha,va=“中心”,旋转模式=“锚定”)
对于(i,j),在np.ndenumerate(df)中的z:
如果z!=0:
文本(j,i,str(z),ha=“center”,va=“center”)
botax.set_标题(“名称共现”)
图1紧_布局图()
plt.show()

不幸的是,顶部标签没有正确对齐,我不知道为什么:

您必须首先将上部x轴的纵横比设置为与下部x轴的纵横比相同。如何做到这一点已经得到了回答。然后,您可以使用
y=1.3
将标题稍微向上提升,使其不会与上部x轴刻度标签重叠

topax = botax.twiny()

aspect0 = botax.get_aspect()
if aspect0 == 'equal':
    aspect0 = 1.0
dy = np.abs(np.diff(botax.get_ylim()))
dx = np.abs(np.diff(botax.get_xlim()))

aspect = aspect0 / (float(dy) / dx)
topax.set_aspect(aspect)

for ax, ha, pos in zip([topax, botax], ["left", "right"], ["top", "bottom"]):
  ax.set_xticks(np.arange(n))
  .....
  .....

botax.set_title("Name Co-Occurrences", y=1.3)

为了标记轴的底部和顶部,不需要双轴。这可能会让这一切变得容易一些。您可以只打开底部和顶部的记号和标签,然后分别旋转和对齐它们

import pandas as pd
import numpy as np
import string
import matplotlib.pyplot as plt

n = 10
names = ['Long Name ' + suffix for suffix in string.ascii_uppercase[:n]]
df = pd.DataFrame(np.random.randint(0, 100, size=(n,n)),
                  columns=names, index=names)

fig = plt.figure()
ax = plt.gca()

im = ax.matshow(df, interpolation='none')
fig.colorbar(im)

ax.set_xticks(np.arange(n))
ax.set_xticklabels(names)
ax.set_yticks(np.arange(n))
ax.set_yticklabels(names)

# Set ticks on both sides of axes on
ax.tick_params(axis="x", bottom=True, top=True, labelbottom=True, labeltop=True)
# Rotate and align bottom ticklabels
plt.setp([tick.label1 for tick in ax.xaxis.get_major_ticks()], rotation=45,
         ha="right", va="center", rotation_mode="anchor")
# Rotate and align top ticklabels
plt.setp([tick.label2 for tick in ax.xaxis.get_major_ticks()], rotation=45,
         ha="left", va="center",rotation_mode="anchor")

ax.set_title("Name Co-Occurrences", pad=55)
fig.tight_layout()
plt.show()

这是一种非常干净的方法,谢谢。您知道自动计算标题填充的方法吗?与类似,只需使用标签的最大高度,而不是图例。您不必填充,因此这是一个标题错误,没有考虑标签的旋转。标题“不动”是一个bug:谢谢你指出它。有关修复方法,请参阅…如何在顶部和底部添加不同的标签?