简体   繁体   English

Matplotlib 将刻度位置与图像像素边界对齐

[英]Matplotlib align tick positions with image pixel boundaries

I am generating images with numpy , using matplotlib to visualize regions I care about, and then using pillow to save them as PNGs.我正在使用matplotlib numpy可视化我关心的区域,然后使用pillow将它们保存为 PNG。 When I am plotting the images, the tick marks and labels are centered on the pixels instead of on pixel boundaries:当我绘制图像时,刻度线和标签以像素而不是像素边界为中心:

在此处输入图像描述

Is there a way I could left/top justify the ticks and labels?有没有办法我可以左/上证明刻度和标签? I've found info on moving the labels, but not the ticks.我找到了有关移动标签的信息,但没有找到刻度。

I have also tried using the axis interface with ax.major_ticklabels.set_ha("left") and ax.major_ticklabels.set_va("top") as documented here but can't get it to work.我也尝试过将轴接口与ax.major_ticklabels.set_ha("left")ax.major_ticklabels.set_va("top")一起使用,如此所述,但无法使其正常工作。 I expected 0 to be right on the edge and 1 right in the middle but I can't get this behavior.我预计0就在边缘, 1就在中间,但我无法得到这种行为。

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

image_size = (2, 2)
data = np.zeros(image_size)
data[0][0] = 255
data[1][1] = 255
plt.xticks([0, 1])
plt.yticks([0, 1])
plt.imshow(Image.fromarray(data).convert("L"))
plt.show()

Here is the solution:这是解决方案:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

image_size = (2, 2)
data = np.zeros(image_size)
data[0][0] = 255
data[1][1] = 255
x= [0,.5]
y= [0,.5]
labels = (0,1)
plt.xticks(x, labels)
plt.yticks(y, labels)
plt.imshow(Image.fromarray(data).convert("L"),extent = [0, 1,0 ,1])
plt.show()

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

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