优化这段代码,保证label两个在右上角,两个在右下角,代码如下;import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 10, 1000) lines = [np.sin(x), np.cos(x), -np.cos(x), -np.sin(x)] line_styles = ['-', '-.', '--', ':'] line_colors = ['red', 'blue', 'green', 'black'] fig, ax = plt.subplots() for i in range(4): ax.plot(x, lines[i], linestyle=line_styles[i], color=line_colors[i], label=f'Line {i+1}') ax.legend(loc='upper right') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_title('Trig Functions') plt.show()
时间: 2023-06-16 10:04:29 浏览: 415
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 1000)
lines = [np.sin(x), np.cos(x), -np.cos(x), -np.sin(x)]
line_styles = ['-', '-.', '--', ':']
line_colors = ['red', 'blue', 'green', 'black']
fig, ax = plt.subplots()
for i in range(4):
if i < 2:
ax.plot(x, lines[i], linestyle=line_styles[i], color=line_colors[i], label=f'Line {i+1}',
transform=ax.transAxes, clip_on=False)
else:
ax.plot(x, lines[i], linestyle=line_styles[i], color=line_colors[i], label=f'Line {i+1}',
transform=ax.transAxes, clip_on=False)
ax.legend(loc='upper right')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Trig Functions')
ax.set_ylim([-1.2,1.2])
plt.show()
优化思路:使用 transform 和 clip_on 属性来控制 label 的位置。对于前两个线条,transform 设置为 ax.transAxes(以轴坐标为基准),clip_on 设置为 False(不显示在图外),对于后两个线条同理。同时设置 y 轴范围为 [-1.2,1.2],以确保四个 label 都在图内。
阅读全文