2017-04-21 85 views
0

我有稀疏的散点图可视化预测值与实际值的比较。值的范围是1-4,并且没有小数点。如何在稀疏散点图中将点的计数添加为标签

我试图plotly迄今与HTE下面的代码(但我还可以使用matplotlib溶液):

my_scatter = go.Scatter(
    x = y_actual, y = y_pred, mode = 'markers', 
    marker = dict(color = 'rgb(240, 189, 89)', opacity=0.5) 
) 

这很好地打印的曲线图(见下文)。我使用不透明度来查看每个点的密度。即如果两点彼此重叠,则点将以较暗的颜色显示。但是,这不够解释。是否可以将每个点的计数添加为标签?在某些交叉路口有一些重叠。我想显示多少点相交。这可以自动使用matplotlibplotly

enter image description here

+0

@ImportanceOfBeingErnest我这一遗憾。我希望它看起来更好! (可能是因为我的英语不好!) – renakre

+1

在matplotlib中没有自动的方式来做你想做的事。 (虽然我不太了解情节)。您可能需要找出哪些点重叠,可能是使用numpy histogram2d或熊猫数据透视表。然后你可以注释点(例如使用matplotlib.text)。 – ImportanceOfBeingErnest

+0

@ImportanceOfBeingErnest您是否有建议使用不同的图表来表示数据? – renakre

回答

1

这个答案使用matplotlib。

首先回答最初的问题:您需要了解数据在给定坐标上产生点的频率以便能够注释点。如果所有值都是整数,则可以使用2d直方图轻松完成。走出hstogram的一会又只选择那些箱,其中计数值是非零和环型标注相应的值:

x = [3, 0, 1, 2, 2, 0, 1, 3, 3, 3, 4, 1, 4, 3, 0] 
y = [1, 0, 4, 3, 2, 1, 4, 0, 3, 0, 4, 2, 3, 3, 1] 

import matplotlib.pyplot as plt 
import numpy as np 

x = np.array(x) 
y = np.array(y) 

hist, xbins,ybins = np.histogram2d(y,x, bins=range(6)) 
X,Y = np.meshgrid(xbins[:-1], ybins[:-1]) 
X = X[hist != 0]; Y = Y[hist != 0] 
Z = hist[hist != 0] 


fig, ax = plt.subplots() 
ax.scatter(x,y, s=49, alpha=0.4) 

for i in range(len(Z)): 
    ax.annotate(str(int(Z[i])), xy=(X[i],Y[i]), xytext=(4,0), 
       textcoords="offset points") 

plt.show() 

enter image description here

然后您可以决定不绘制所有点,但结果从它提供改变散点的颜色和大小的机会直方图化,

ax.scatter(X,Y, s=(Z*20)**1.4, c = Z/Z.max(), cmap="winter_r", alpha=0.4) 

enter image description here

由于所有的值都是整数,你也可以选择图像的情节,

fig, ax = plt.subplots() 
ax.imshow(hist, cmap="PuRd") 

for i in range(len(Z)): 
    ax.annotate(str(int(Z[i])), xy=(X[i],Y[i]), xytext=(0,0), color="w", 
       ha="center", va="center", textcoords="offset points") 

enter image description here

没有necesity计算出现的次数,另一种选择是使用hexbin情节。这给点稍微不准确的位置,杜对六边形分档,但我仍然想提这个选项。

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

x = np.array(x) 
y = np.array(y) 

fig, ax = plt.subplots() 

cmap = plt.cm.PuRd 
cmaplist = [cmap(i) for i in range(cmap.N)] 
cmaplist[0] = (1.0,1.0,1.0,1.0) 
cmap = matplotlib.colors.LinearSegmentedColormap.from_list('mcm',cmaplist, cmap.N) 

ax.hexbin(x,y, gridsize=20, cmap=cmap, linewidth=0) 

plt.show() 

enter image description here

+0

感谢您的详细回复! – renakre