Matplotlib绘图旁文本框显示不全,如何调整绘图区域适配显示?
解决方案
你可以通过调整子图的画布占比预留右侧文本空间,同时固定二者的比例,只需修改两处代码即可实现:
- 在创建画布和子图后添加
fig.subplots_adjust(right=0.7),该参数表示绘图区域的右边界停在画布总宽度的70%位置,剩余30%的右侧空间用于放置文本框,窗口缩放时该占比会自动保持不变,你可以根据文本的实际长度调整这个数值,文本越长可将right设置得更小。 - 将文本的x坐标从
1调整为1.02,给文本和绘图区域之间留出少量间距,避免贴边。
修改后的完整代码如下:
import numpy as np import matplotlib.pyplot as plt arr_len = 932826 x = np.random.uniform(low=0, high=4496, size=arr_len) y = np.random.uniform(low=-74, high=492, size=arr_len) z = np.random.uniform(low=-30, high=97, size=arr_len) # Check points bin_x = 10 bin_y = 10 x1 = np.linspace(x.min(), x.max(), bin_x) y1 = np.linspace(y.min(), y.max(), bin_y) def return_val(x, y, z, x1, y1, i, j): idx = np.logical_and(np.logical_and(x > x1[i - 1], x < x1[i]), np.logical_and(y > y1[j - 1], y < y1[j])) if np.count_nonzero(idx) == 0: return np.nan else: return np.mean(z[idx]) z1 = np.zeros((len(x1), len(y1))) for i in range(1, len(x1)): for j in range(1, len(y1)): z1[i - 1, j - 1] = return_val(x, y, z, x1, y1, i, j) z1 = z1.transpose() fig, ax = plt.subplots() # 新增行:调整子图右侧预留空间 fig.subplots_adjust(right=0.7) img = ax.pcolormesh(x1, y1, z1) # cbar = plt.colorbar(img) textbox = '\n'.join([ 'All plot description goes here: ', 'File Name: ', '', 'Folder path: ', 'List of big files processed: ', 'Dataset name: ', '', 'Filter: ', 'Grouping: ', 'Files which are bigger in size than 2000 GB : ', '', '...', '...', '...', ]) bbox = dict(boxstyle='square', facecolor='lavender', alpha=0.5) # 修改x坐标从1为1.02 fig.text(1.02, 1, textbox, fontsize=10, transform=ax.transAxes, bbox=bbox, verticalalignment='top') plt.show()
如果后续需要更灵活的布局控制,也可以使用matplotlib.gridspec来划分画布的网格区域,分别给热力图和文本分配固定比例的网格。
内容的提问来源于stack exchange,提问作者Masoom Kumar
相关产品推荐
相关产品推荐

