Python 与直方图条形颜色相同的高斯拟合

Python gaussian fit with same color as bars of histogram

我使用 pyplot 中的函数 plot()hist()(没有任何颜色定义)生成以下图形:

将包含更多数据集。这就是为什么我想对拟合曲线和相关的直方图使用相同的颜色,以使其在一定程度上有所区别。

我找不到与之相关的任何内容。

为了确保绘图和直方图具有相同的颜色,我的建议是固定绘图和最佳拟合线的颜色。 如果你看这里的例子 http://matplotlib.org/1.2.1/examples/pylab_examples/histogram_demo.html 然后在 python pyplot http://matplotlib.org/1.2.1/api/pyplot_api.html?highlight=hist#matplotlib.pyplot.hist

文档中

matplotlib.pyplot.hist 方法有一个 kwarg 颜色,允许您为直方图选择所需的颜色。在示例中,他们设置了 facecolor='green'

然后为了获得最佳拟合线,您可以选择以相同颜色绘制它。我需要查看代码以提供更精确的指示。但是,如果我们回到这里的示例,行属性设置为:

l = plt.plot(bins, y, 'r--', linewidth=1)

因此,如果我们希望拟合线像直方图的其余部分一样呈绿色,我们将使用:

l = plt.plot(bins, y, 'r--', linewidth=1, color = 'green')

希望这对您有所帮助,如果您没有 post 任何代码行,就无法给您更具体的提示。

我找到了使用

的解决方案
plt.gca().set_color_cycle(None)

感谢Reset color cycle in Matplotlib

下面的代码应该开箱即用,可以完成我关于高斯拟合的问题,颜色与直方图的条形相同

import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np

list_of_lists = []

for i in range(2):
    list = np.random.normal(0, 1, 100)
    list = list.tolist()
    list_of_lists.append(list)

plt.figure()
plt.hist(list_of_lists, bins = 10, normed=True)

numb_lists = len(list_of_lists)

plt.gca().set_color_cycle(None)

for i in range(0, numb_lists):
    list = list_of_lists[i][:]
    mean = np.mean(list)
    variance = np.var(list)
    sigma = np.sqrt(variance)
    x = np.linspace(min(list), max(list), 100)
    plt.plot(x, mlab.normpdf(x, mean, sigma))