使用python繪製散點密度圖(散點圖並標示密度)

原文鏈接:http://blog.sina.com.cn/s/blog_4a238ec20102v8yd.html   
 

   

 

最初遇到這個問題的時候,找到的大答案是繪製contour圖,比如:

http://stackoverflow.com/questions/24119920/how-to-plot-a-density-map-in-python?rq=1​

這當然很漂亮,但是這需要有三列數字來標示一個平面;但其實我的問題是僅有兩列數的時候如何標示密度:

方法一,使用hist2d:

例子來源: http://matplotlib.org/examples/pylab_examples/hist2d_log_demo.html

from matplotlib.colors import LogNorm

​from pylab import *

​#normal distribution center at x=0 and y=5

​x = randn(100000)

​y = randn(100000)+5

​hist2d(x, y, bins=40, norm=LogNorm())

​colorbar()

​show()

 

方法二,使用hexbin

​參見這個例子:http://matplotlib.org/examples/pylab_examples/hexbin_demo.html​

方法三,使用gaussian_kde

關於gaussian_kde的介紹可以參見這裏:http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html, 簡而言之,這是使用Kernel density estimation的方法,估計出每個位置的密度值。

import numpy as np

​import matplotlib.pyplot as plt

​from scipy.stats import gaussian_kde

​# Generate fake data

​x = np.random.normal(size=1000)

​y = x *3+ np.random.normal(size=1000)

​# Calculate the point density

​xy = np.vstack([x,y])

​z = gaussian_kde(xy)(xy)

​fig, ax = plt.subplots()

​ax.scatter(x, y, c=z, s=100, edgecolor='')

​plt.show()

案例來源:http://stackoverflow.com/questions/20105364/how-can-i-make-a-scatter-plot-colored-by-density-in-matplotlib

還有其他文章可供參考:

python matplotlib繪製散點密度圖

如何在matplotlib中繪製以密度着色的散點圖?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章