簡體   English   中英

如何在散點圖中繪制線條

[英]How to draw line inside a scatter plot

我無法相信這是如此復雜,但我現在嘗試和谷歌搜索了一段時間。

我只是想用一些圖形功能來分析我的散點圖。 對於初學者,我想簡單地添加一行。

所以,我有幾(4)分,我想在其中添加一行,就像在這個情節中一樣(來源: http//en.wikipedia.org/wiki/FileROC_space-2.png

在此輸入圖像描述

現在,這不起作用。 坦率地說,文檔-examples-gallery組合和matplotlib的內容是一個糟糕的信息來源。

我的代碼基於圖庫中的簡單散點圖:

# definitions for the axes
left, width = 0.1, 0.85 #0.65
bottom, height = 0.1, 0.85 #0.65
bottom_h = left_h = left+width+0.02

rect_scatter = [left, bottom, width, height]

# start with a rectangular Figure
fig = plt.figure(1, figsize=(8,8))
axScatter = plt.axes(rect_scatter)

# the scatter plot:
p1 = axScatter.scatter(x[0], y[0], c='blue', s = 70)
p2 = axScatter.scatter(x[1], y[1], c='green', s = 70)
p3 = axScatter.scatter(x[2], y[2], c='red', s = 70)
p4 = axScatter.scatter(x[3], y[3], c='yellow', s = 70)
p5 = axScatter.plot([1,2,3], "r--")

plt.legend([p1, p2, p3, p4, p5], [names[0], names[1], names[2], names[3], "Random guess"], loc = 2)

# now determine nice limits by hand:
binwidth = 0.25
xymax = np.max( [np.max(np.fabs(x)), np.max(np.fabs(y))] )
lim = ( int(xymax/binwidth) + 1) * binwidth

axScatter.set_xlim( (-lim, lim) )
axScatter.set_ylim( (-lim, lim) )

xText = axScatter.set_xlabel('FPR / Specificity')
yText = axScatter.set_ylabel('TPR / Sensitivity')

bins = np.arange(-lim, lim + binwidth, binwidth)
plt.show()

一切都有效,除了p5是一條線。

現在該如何運作? 這里有什么好的做法?

plot采用y值並使用x作為索引數組0..N-1或x和y值,如文檔中所述。 所以你可以使用

p5 = axScatter.plot((0, 1), "r--")

在你的代碼中繪制線條。

但是,你要求“良好做法”。 以下代碼(希望如此)顯示了一些“良好實踐”以及matplotlib的一些功能來創建您在問題中提到的情節。

import numpy as np
import matplotlib.pyplot as plt 

# create some data
xy = np.random.rand(4, 2)
xy_line = (0, 1)

# set up figure and ax
fig, ax = plt.subplots(figsize=(8,8))

# create the scatter plots
ax.scatter(xy[:, 0], xy[:, 1], c='blue')
for point, name in zip(xy, 'ABCD'):
    ax.annotate(name, xy=point, xytext=(0, -10), textcoords='offset points',
                color='blue', ha='center', va='center')
ax.scatter([0], [1], c='black', s=60)
ax.annotate('Perfect Classification', xy=(0, 1), xytext=(0.1, 0.9),
            arrowprops=dict(arrowstyle='->'))

# create the line
ax.plot(xy_line, 'r--', label='Random guess')
ax.annotate('Better', xy=(0.3, 0.3), xytext=(0.2, 0.4),
            arrowprops=dict(arrowstyle='<-'), ha='center', va='center')
ax.annotate('Worse', xy=(0.3, 0.3), xytext=(0.4, 0.2),
            arrowprops=dict(arrowstyle='<-'), ha='center', va='center')
# add labels, legend and make it nicer
ax.set_xlabel('FPR or (1 - specificity)')
ax.set_ylabel('TPR or sensitivity')
ax.set_title('ROC Space')
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.legend()
plt.tight_layout()
plt.savefig('scatter_line.png', dpi=80)

scatter_with_line.png

順便說一句:我認為matplotlibs文檔現在非常有用。

p5行應該是:

p5 = axScatter.plot([1,2,3],[1,2,3], "r--")

參數1是x值的列表,參數2是y值的列表

如果您只想要一條直線,則只需要為該線的末端提供值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM