prosperityworld 2024-12-10 09:59 采纳率: 0%
浏览 3

(标签-matplotlib|关键词-matplot)


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()

求指教,如何改变上述代码,让第一个矩形从左上角开始,而不是左下角

  • 写回答

1条回答 默认 最新

  • JavaPub-rodert 领域专家: 后端开发技术领域 2024-12-10 10:21
    关注

    本答案参考 多次询问 ChatGPT-3.5 后选择的最佳回答,若是满意,还请采纳,谢谢

    要让第一个矩形从左上角开始,你需要调整y_positions的计算方式,使其从y轴的顶部开始而不是底部。以下是修改后的代码段:

    # 计算每个格子的x和y位置
    x_positions = np.arange(num_cols) * (rectangle_width + spacing_x)  # x位置,无需改变
    
    # y位置需要调整,以确保第一个盒子的顶部与y轴顶部对齐
    y_positions = np.arange(num_rows) * (rectangle_height + spacing_y)  # 从顶部开始计算y位置
    

    同时,你需要调整ax.set_ylim的设置,以确保y轴的显示范围从顶部开始:

    # 设置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(max(y_positions) - rectangle_height,  # y轴从最大的y位置开始
                min(y_positions) + rectangle_height * num_rows)  # y轴结束位置考虑到最后一个盒子的顶部和间隔
    

    这样修改后,第一个矩形就会从左上角开始绘制。

    评论

报告相同问题?

问题事件

  • 创建了问题 12月10日