[英]Matplotlib labels are overlapping
我有一個圖像,其中每列都有一個關聯的屬性。 我想繪制圖像並用其屬性值標記每列。 這是一個顯示我的意思的簡單代碼:
import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage.filters import gaussian_filter
np.random.seed(200)
cols = 600
attr = list('abcdefghijklmnopqrstuvwxyz') * cols
attr = labels[:cols]
img = gaussian_filter(np.random.rand(400, cols), 100)
plt.imshow(img, cmap='inferno')
plt.xticks(np.arange(cols), attr)
plt.show()
下面生成的圖像顯示了X標簽的混亂程度。 我想要的是顯示一些標簽,這些標簽在與繪圖交互時會更新,例如縮放和平移。
我認為這是可能的原因是因為maplotlib的默認行為是正確的(當沒有設置xticks時)。 它以間隔顯示列號,因此標簽不會重疊,並在縮放和平移時更新。
所以,我的問題是:是否可以使用自定義標簽獲取默認的matplotlib標簽行為?
你想要的是稱為刻度格式 。 在這種情況下,您可以創建FuncFormatter
的實例並將其分配給主要刻度。
首先,您需要將FuncFormatter
添加到導入中:
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np
from scipy.ndimage.filters import gaussian_filter
您需要一個獲取刻度值及其位置並返回刻度標簽的函數。 你不需要這里的位置,但無論如何它將被傳遞給函數。 確保該函數可以處理意外的滴答值(我使用了matplotlib 2.0.0b4,並在600處打勾)。
cols = 600
letters = list('abcdefghijklmnopqrstuvwxyz')
attr = (letters * (1 + cols // len(letters)))[:cols]
def format_tick(labels):
def get_label(x, pos):
try:
return labels[int(round(x))]
except IndexError:
return ''
return get_label
使用format函數創建FuncFormatter
實例:
formatter = FuncFormatter(format_tick(attr))
將formatter
設置為繪圖的主要格式化程序:
rs = np.random.RandomState(seed=200)
img = gaussian_filter(rs.rand(400, cols), 100)
plt.imshow(img, cmap='inferno')
plt.gca().xaxis.set_major_formatter(formatter)
當然,這種標簽對您的樣本數據沒有任何意義。 我確信你的實際用例有更好的方法,無論它是什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.