【问题标题】:Matplotlib: Increase ax.matshow width/height, and set color map (cmap) to transparentMatplotlib:增加 ax.matshow 宽度/高度,并将颜色图(cmap)设置为透明
【发布时间】:2019-04-27 11:13:06
【问题描述】:

我有一个由随机值组成的矩阵,我用ax.matplot 绘制了它,其中每个矩阵单元格的值都绘制在矩阵单元格的中心,我需要增加绘图的大小(特别是宽度)并将颜色图(cmap)设置为“透明”,其中矩阵图的单元格将为white,单元格中心的矩阵值为black。

代码:

import numpy as np
import matplotlib.pyplot as plt

low_dim = 0
high_dim = 20

matrix = np.random.randint(low_dim, high_dim, (high_dim,high_dim))
print (matrix)
fig, ax = plt.subplots()

ax.matshow(matriz, cmap=None,interpolation='nearest')

for i in xrange(20):
    for j in xrange(20):
        number = matrix[j,i]
        ax.text(i, j, str(number), va='center', ha='center')


plt.show()

编辑

就是代码中的matrix(https://i.stack.imgur.com/e3mGO.png(ma​​trix),用命令matrix = np.random.randint(low_dim, high_dim, (high_dim,high_dim))生成的矩阵,图片来自控制台。

我尝试更改fig,ax = plt.subplot() 中的figsize,但没有任何改变。我也设置了cmap = none,但什么也没发生。

另一个问题是,在第一张图中,x和y轴的索引中的数字从0到15不等,步进5,比如0、5、10、15(我'已将其标记为红色)。但在第二张图片中(也用红色标记),值是从 0 到 19,没有步长。如果可能的话,我需要得到第二张图片的结果,索引从 0 到 19 不等,没有步骤。

图片 1:我得到了什么: https://i.stack.imgur.com/mlExQ.png

图2:我需要得到的东西:https://i.stack.imgur.com/T3CC4.png

【问题讨论】:

  • 您的代码中的matrix 是什么?如果你使用 Python 2.7,你应该相应地标记问题。
  • 我已经编辑过了。
  • 我希望 this example 能有所帮助。

标签: python-2.7 matplotlib axes colormap


【解决方案1】:

matshow 接受 origin 和 alpha 的参数。剩下的只是设置刻度和标签。

ax.matshow(matrix, origin='lower', alpha=0, cmap=None, interpolation='nearest')

tick_labels = range(high_dim)
ax.set_xticks([], minor=False)
ax.set_xticks(np.arange(-.5, 20, 1), minor=True)
ax.set_yticks([], minor=False)
ax.set_yticks(np.arange(-.5, 20, 1), minor=True)
ax.set_xticklabels([], minor=False)
ax.set_xticklabels(tick_labels, minor=True)
ax.set_yticklabels([], minor=False)
ax.set_yticklabels(tick_labels, minor=True)
ax.xaxis.set_ticks_position('bottom')
ax.grid(which='minor', color='grey', linestyle='-', linewidth=1)

【讨论】:

  • 我运行了代码,结果是我之前遇到的一个小问题,无法解决:这是控制台中的结果矩阵(我首先在控制台中打印它以检查情节是否代码很好)---> i.imgur.com/JpS5ZJF.jpg,这就是生成的情节---> i.imgur.com/4RRiXU3.jpg。请注意,这些线是“颠倒的”,y 轴的索引也是如此(顶部为 19,底部为 0)。我怎么能做到这一点?
  • 如果想让你的原点在左上角,可以设置origin='upper'
猜你喜欢
  • 1970-01-01
  • 2011-06-02
  • 1970-01-01
  • 2014-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
相关资源
最近更新 更多