简体   繁体   中英

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
  • PyCharm 2018.1

As the comments indicated the problem seems to go away at higher DPI, for future users this is shown below,

50 DPI - Figsize 8, 6

100 DPI - Figsize 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

50 DPI - Figsize 20,16

100 DPI - Figsize 20,16

300 DPI - Figsize 20,16

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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