gpt4 book ai didi

python - 创建绘图后更新它

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:00 24 4
gpt4 key购买 nike

在我正在使用的Python教科书中,我读到:“图表的每个视觉方面都可以更改其默认值。您可以在创建绘图时指定这些内容;大多数也可以稍后更改。”

因此创建一个 .py 文件

# simple_plot.py
import numpy as np, matplotlib.pyplot as plt
num_points = 5
x_min, x_max = 0, 4
5 x_values = np.linspace(x_min, x_max, num_points)
y_values = x_values**2
plt.plot(x_values, y_values)

并运行它,给出所需的图。现在在控制台中输入,例如

plt.plot(x_values,y_values,'r--o')

绘制一条红色虚线,每个点都有红色圆圈。但是我无法理解为什么在控制台中输入(而不是在最初创建的脚本中添加说明)类似

plt.title("My first plot", size=24, weight='bold')
plt.xlabel("speed")
plt.ylabel("kinetic energy")

不更新情节。非常感谢。

最佳答案

我假设您通过调用 myscript.py 来运行脚本(我们称之为 run myscript.py )在 IPython 控制台中,使用 %matplotlib inline选项已激活。

这将根据需要将图形绘制到控制台中。然而,一旦绘制了图形,您就失去了对它的引用。调用plt.plot(x_values,y_values,'r--o')创建一个新图形,并且 plt.title(..)还有一个。

您可以做的一件事就是更多地以面向对象的方式工作。 IE。创建图形并在 myscript.py 中保留引用像这样的文件:

import numpy as np, matplotlib.pyplot as plt
num_points = 5
x_min, x_max = 0, 4
x_values = np.linspace(x_min, x_max, num_points)
y_values = x_values**2

fig, ax = plt.subplots()
ax.plot(x_values, y_values)

然后在控制台中您可以输入

ax.set_title("My Title")
ax.set_xlabel("MyLabel")

并随时输入 fig 显示具有更新属性的图形.

enter image description here

关于python - 创建绘图后更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42457360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com