gpt4 book ai didi

python - Matplotlib 具有自定义颜色的奇怪图形

转载 作者:行者123 更新时间:2023-11-30 22:22:47 24 4
gpt4 key购买 nike

我在使用 matplotlib 绘制具有自定义颜色的函数时遇到了一个奇怪的问题。我的图像底部有一个奇怪的红色图表。这是我的代码:

import matplotlib.pyplot as plt
import numpy as np

def graph(formulas, x1, x2):

x = np.linspace(x1, x2, 400)
for i, formula in enumerate(formulas):
print i
y = formula(x)
plt.plot(x, y,(1.0, 0.25, 0.25))
plt.show()

def parabola(a):
return (lambda x: a * x**2)

graph((parabola(1.0),), -5, 5)

这里是 matplotlib 自定义颜色文档:https://matplotlib.org/users/colors.html

这是生成的图表:

我不知道出了什么问题。当我使用 'r' 作为我的颜色时,图形效果完美。

编辑:我刚刚结束使用默认颜色。但如果有人能解释发生了什么,我仍然会很感兴趣。

最佳答案

您的问题是 plot 命令的“多语法”。将参数传递给绘图命令的可能方法之一是(直接来自 matplotlib documentation ):

import numpy as np
import matplotlib.pyplot as plt

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

该命令绘制三条曲线,(每条曲线)各自的第一和第二个参数是 x 和 y 坐标,各自的第三个参数是线条颜色和风格。您还可以省略线条样式参数,

plt.plot(t, t, t, t**2, t, t**3)

在这种情况下,matplotlib 使用默认颜色。在您的情况下,第三个参数(您打算将其作为颜色)被解释为第二条曲线的坐标。由于只有一个可迭代对象,因此它被解释为曲线的 y 值,并且 x 值被“自动填充”为 (0,1,2)。要在示例中获得所需的行为,请显式添加关键字 color:

plt.plot(x, y, color=(1.0, 0.25, 0.25))

然后结果看起来如预期:

result of the code posted by the OP with the plot command corrected as indicated above

关于python - Matplotlib 具有自定义颜色的奇怪图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48218408/

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