import matplotlib.pyplot as plt
import numpy as np
# 设置格子参数
num_rows = 4 # 行数
num_cols = 6 # 列数
rectangle_width = 0.4 # 格子宽度(相对于x轴每行的比例)
rectangle_height = 0.2 # 格子高度(相对于y轴的比例)
spacing_x = 0.1 # 格子之间的x轴间隔(相对于x轴每行的比例)
spacing_y = 0.3 # 两排格子之间的y轴间隔(相对于y轴的比例)
# 生成一些示例数据
ports = [f"Port {i + 1}" for i in range(num_rows * num_cols)]
negative_pressures = np.random.uniform(-50, 0, num_rows * num_cols) # 生成-50到0之间的随机负压值
# 设置图形大小和边距
fig, ax = plt.subplots()
fig.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)
# 计算每个格子的x和y位置
x_positions = np.arange(num_cols) * (rectangle_width + spacing_x) # x位置,无需改变
# y位置需要调整,以确保第一个盒子的顶部与y轴顶部对齐
y_positions = np.repeat(np.arange(num_rows), num_cols) * (rectangle_height + spacing_y) - rectangle_height # 减去rectangle_height以对齐顶部
# 设置x轴和y轴的显示范围(应该在循环之外设置一次)
ax.set_xlim(min(x_positions) - rectangle_width / 2 - spacing_x / 2,
max(x_positions) + rectangle_width / 2 + spacing_x / 2)
ax.set_ylim(min(y_positions) + rectangle_height / 2 + spacing_y / 2, # y轴从最小的y位置开始
max(y_positions)) # y轴结束位置考虑到最后一个盒子的底部和间隔
# 绘制格子和文本
for i, (x, y, port, pressure) in enumerate(zip(x_positions, y_positions, ports, negative_pressures)):
# 绘制格子
rect = plt.Rectangle((x - rectangle_width / 2, y - rectangle_height / 2), rectangle_width, rectangle_height,
edgecolor='black', facecolor='lightblue')
ax.add_patch(rect)
# 在格子上方显示端口号(稍微调整y位置以避免与格子重叠)
ax.text(x, y + rectangle_height + 0.02, port, horizontalalignment='center', verticalalignment='bottom')
# 在格子中心位置显示负压值(转换为字符串并格式化)
ax.text(x, y - rectangle_height / 2 + rectangle_height / 4, f"{pressure:.2f}", horizontalalignment='center', verticalalignment='center')
# 隐藏x轴和y轴的刻度线和标签(如果需要的话)
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
# 显示网格线(可选)
ax.grid(True, which='both', linestyle='--', linewidth=0.5)
# 显示图形
plt.show()
求指教,如何改变上述代码,让第一个矩形从左上角开始,而不是左下角