2017-04-21 87 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