简体   繁体   English

Python Matplotlib - 未对齐的网格线和颜色填充

[英]Python Matplotlib - Misaligned Grid Lines and Color Fills

I'm using the following code to produce a sort of binary heatmap: 我正在使用以下代码生成一种二进制热图:

import numpy as np
import matplotlib.colors as mlc
import matplotlib.pyplot as mlp

states = ['AAAA', 'BBBB', 'CCCC', 'DDDD']
walk = [1, 2, 3, 2, 3, 2, 3, 2, 3, 2]

states_len = len(states)
walk_len = len(walk)

img = np.zeros((states_len, walk_len), dtype=float)

for i, s in enumerate(walk):
    img[s, i] = 1.0

figure, ax = mlp.subplots()

color_map = mlc.LinearSegmentedColormap.from_list('ColorMap', [(1.000, 1.000, 1.000), (0.984, 0.501, 0.447)])
ax.imshow(img, cmap=color_map, interpolation='none')

ax.set_xlabel('Steps', fontsize=13)
ax.set_xticks(np.arange(0, walk_len, 1))
ax.set_xticks(np.arange(-0.5, walk_len, 1), minor=True)
ax.set_xticklabels(np.arange(1, walk_len + 1, 1))

ax.set_ylabel('States', fontsize=13)
ax.set_yticks(np.arange(0, states_len, 1))
ax.set_yticks(np.arange(-.5, states_len, 1), minor=True)
ax.set_yticklabels(states)

ax.grid(which='minor', color='k')

ax.set_title('Walkplot (Sequence)', fontsize=15, fontweight='bold')

And it's producing weird results: 它产生了奇怪的结果:

截图

As you may notice, the color spots look not lined up with respect to the grid squares. 正如您可能注意到的那样,颜色斑点看起来没有相对于网格方块排列。 On the top of that, sometimes grid lines don't have a uniform size, some looks bigger than others. 最重要的是,有时网格线的大小不均匀,有些看起来比其他大。

I think it must be related to the aspect ratio or to the figure size, but I'm clueless about a potential fix. 我认为它必须与纵横比或数字大小相关,但我对一个潜在的修复无能为力。 How can I solve this issue? 我该如何解决这个问题?

My current setup: 我目前的设置:

  • Python 3.6 x64 Python 3.6 x64
  • PyCharm 2018.1 PyCharm 2018.1

As the comments indicated the problem seems to go away at higher DPI, for future users this is shown below, 由于评论表明问题似乎在DPI较高时消失,对于未来的用户,如下所示,

50 DPI - Figsize 8, 6 50 DPI - 图8,6

100 DPI - Figsize 8. 6 100 DPI - 图8。6

However it is also influenced by the figsize parameter, set either with matplotlib rcParams or with figsize(height, width) in construction of the figure - larger figures require higher DPI for the display problem to disappear (though it may be necessary to view the full size images to see the effect, instead of the inline display), ie 然而,它也通过影响figsize参数,设置或者与matplotlib rcParamsfigsize(height, width)在结构上的figure -较大的数字需要较高的DPI用于显示问题消失(尽管它可能需要查看完整的尺寸图像,以查看效果,而不是内联显示),即

50 DPI - Figsize 20,16 50 DPI - 图20,16

100 DPI - Figsize 20,16 100 DPI - 图20,16

300 DPI - Figsize 20,16 300 DPI - 图20,16

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM