# 如何在matplotlib中创build密度图？

``data = c(rep(1.5, 7), rep(2.5, 2), rep(3.5, 8), rep(4.5, 3), rep(5.5, 1), rep(6.5, 8)) plot(density(data, bw=0.5))` `

` `import matplotlib.pyplot as plt data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8 plt.hist(data, bins=6) plt.show()` `

Sven展示了如何使用Scipy中的`gaussian_kde`类，但是你会注意到它看起来不像你用R生成的东西。这是因为`gaussian_kde`试图自动推断带宽。 您可以通过更改`gaussian_kde`类的函数`covariance_factor`来使用带宽。 首先，这里是你没有改变的function：

` `import matplotlib.pyplot as plt import numpy as np from scipy.stats import gaussian_kde data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8 density = gaussian_kde(data) xs = np.linspace(0,8,200) density.covariance_factor = lambda : .25 density._compute_covariance() plt.plot(xs,density(xs)) plt.show()` `

` `import numpy as np import seaborn as sns data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8 sns.set_style('whitegrid') sns.kdeplot(np.array(data), bw=0.5)` `

` `import matplotlib.pyplot as plt import numpy from scipy import stats data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8 density = stats.kde.gaussian_kde(data) x = numpy.arange(0., 8, .1) plt.plot(x, density(x)) plt.show()` `

` `import pandas as pd data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8 df = pd.DataFrame(data) df.plot(kind='density')` `

` `import seaborn as sns data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8 sns.distplot(data, hist=False)` `