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

标签 python matplotlib

我在使用 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/

相关文章:

Python 包依赖树

python - 每次在 python 中使用 subprocess.call 发送 linux 电子邮件时都会得到一个空体

python - 将字符串向左旋转 n 个字符,特殊字符除外

python-3.x - 将列添加到数据框(Pandas)时出现键错误

python - 是否有任何方法可以调整整个图的大小以及 matplotlib 或 seaborn 中的字体大小和线宽?

python - 如何在 matplotlib 中并排绘制堆叠直方图?

python - 在 matplotlib 中使用边距自动缩放

python - 如何找出每种产品在 Pandas DataFrame 中的销量

python - 如何使用函数跳出 for 循环?

python - Python 中的 matplotlib 问题