【发布时间】:2017-10-10 11:05:55
【问题描述】:
我使用 pyplot 中的 plot() 和 hist() 函数(没有任何颜色定义)生成以下图形:
将包含更多数据集。这就是为什么我想对拟合曲线和相关的直方图使用相同的颜色,以使其具有一定的可区分性。
我找不到任何相关的东西。
【问题讨论】:
标签: python matplotlib histogram data-fitting gauss
我使用 pyplot 中的 plot() 和 hist() 函数(没有任何颜色定义)生成以下图形:
将包含更多数据集。这就是为什么我想对拟合曲线和相关的直方图使用相同的颜色,以使其具有一定的可区分性。
我找不到任何相关的东西。
【问题讨论】:
标签: python matplotlib histogram data-fitting gauss
我找到了一个使用
的解决方案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))
【讨论】:
为了确保绘图和直方图具有相同的颜色,我的建议是您修复绘图和最佳拟合线的颜色。 如果你看这里的例子http://matplotlib.org/1.2.1/examples/pylab_examples/histogram_demo.html 然后在pyplot的python文档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')
希望这会有所帮助,如果您不发布任何代码行,则无法为您提供更具体的提示。
【讨论】: