matplotlib.patches.Rectangle 生成线宽大小不等的矩形

问题描述 投票:0回答:1

我正在使用 matplotlib 使用

matplotlib.patches.Rectangle
将矩阵的列绘制为单独的矩形。不知何故,所有“内部”线都比“外部”线宽?有人知道这是怎么回事吗?这与这个Github问题有关吗?

这是 MRE:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.patches as patches

# set seed
np.random.seed(42)

# define number of cols and rows
num_rows = 5
num_cols = 5

# define gap size between matrix columns
column_gap = 0.3

# define linewidth
linewidth = 5

# Determine the width and height of each square cell
cell_size = 1  # Set the side length for each square cell

# Initialize the matrix
matrix = np.random.rand(num_rows, num_cols)

# Create the plot
fig, ax = plt.subplots(figsize=(8,6))

# Create a seaborn color palette (RdYlBu) and reverse it
palette = sns.color_palette("RdYlBu", as_cmap=True).reversed()

# Plot each cell individually with column gaps
for i in range(num_rows):
    for j in range(num_cols):
        
        # Compute the color for the cell
        color = palette(matrix[i, j])
        
        if column_gap > 0:
            edgecolor = 'black'
        else:
            edgecolor = None
        
        # Add a rectangle patch with gaps only in the x-direction
        rect = patches.Rectangle(
            (j * (cell_size + column_gap), i * cell_size),  # x position with gap applied to columns only
            cell_size,                                      # width of each cell
            cell_size,                                      # height of each cell
            facecolor=color,
            edgecolor=edgecolor,
            linewidth=linewidth
        )
        
        ax.add_patch(rect)

if column_gap > 0:
    
    # Remove the default grid lines and ticks
    ax.spines[:].set_visible(False)

# Set axis limits to fit all cells
ax.set_xlim(0, num_cols * (cell_size + column_gap) - column_gap)
ax.set_ylim(0, num_rows * cell_size)

# Disable x and y ticks
ax.set_xticks([])
ax.set_yticks([])

fig.show()

产生:

rectangles with unequal linewidths

python matplotlib rectangles
1个回答
0
投票

矩形的边缘被轴边界剪切。

clip_on=False
添加到
Rectangle

        rect = patches.Rectangle(
            (j * (cell_size + column_gap), i * cell_size),  # x position with gap applied to columns only
            cell_size,                                      # width of each cell
            cell_size,                                      # height of each cell
            facecolor=color,
            edgecolor=edgecolor,
            linewidth=linewidth,
            clip_on=False,
        )

输出(用于演示的小尺寸):

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.