优化这段代码,将两个图形合并成一个 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'] # 创建第一个坐标轴,画 part A 和 part B fig, ax1 = plt.subplots() ax1.plot(x, lines[0], linestyle=line_styles[0], color=line_colors[0], label=f'part A') ax1.plot(x, lines[1], linestyle=line_styles[1], color=line_colors[1], label=f'part B') ax1.legend(loc='upper right') # 创建第二个坐标轴,画 part C 和 part D fig, ax2 = plt.subplots() ax2.plot(x, lines[2], linestyle=line_styles[2], color=line_colors[2], label=f'part C') ax2.plot(x, lines[3], linestyle=line_styles[3], color=line_colors[3], label=f'part D') ax2.legend(loc='lower right') plt.show()
时间: 2023-06-16 15:03:55 浏览: 102
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()
ax.plot(x, lines[0], linestyle=line_styles[0], color=line_colors[0], label=f'part A')
ax.plot(x, lines[1], linestyle=line_styles[1], color=line_colors[1], label=f'part B')
ax.plot(x, lines[2], linestyle=line_styles[2], color=line_colors[2], label=f'part C')
ax.plot(x, lines[3], linestyle=line_styles[3], color=line_colors[3], label=f'part D')
ax.legend(loc='upper right')
plt.show()
相关问题
import torch import numpy as np import matplotlib.pyplot as plt x = np.linspace(-10, 10, num=100) act = torch.nn.SiLU() pred = act(torch.from_numpy(x)) y = pred.detach().numpy() plt.plot(x, y) plt.show()使图像一直停留界面
可以在代码最后加上`plt.waitforbuttonpress()`或者`plt.pause(0.001)`,来使图像停留在界面上。例如:
```
import torch
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10, 10, num=100)
act = torch.nn.SiLU()
pred = act(torch.from_numpy(x))
y = pred.detach().numpy()
plt.plot(x, y)
plt.show()
plt.waitforbuttonpress()
```
或者
```
import torch
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10, 10, num=100)
act = torch.nn.SiLU()
pred = act(torch.from_numpy(x))
y = pred.detach().numpy()
plt.plot(x, y)
plt.show()
plt.pause(0.001)
```
这样就可以使图像一直停留在界面上,直到用户手动关闭。
%matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') import numpy as np 如何将这段代码的图形显示在新窗口,提供代码
你可以使用 `%matplotlib qt` 命令将图形显示在新窗口中。同时,需要在代码最后添加 `plt.show()` 命令来显示图形窗口。
完整代码如下:
```python
%matplotlib qt
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
x = np.linspace(0, 10, 1000)
y = np.sin(x)
plt.plot(x, y)
plt.show()
```
运行该代码后,会弹出一个新窗口来显示绘制的图形。