Hướng dẫn how do you label data points in a scatter plot in python? - làm thế nào để bạn gắn nhãn các điểm dữ liệu trong một biểu đồ phân tán trong python?

Tôi rất thích nói thêm rằng bạn thậm chí có thể sử dụng mũi tên /hộp văn bản để chú thích các nhãn. Đây là những gì tôi muốn nói:

import random
import matplotlib.pyplot as plt


y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.subplots()
ax.scatter(z, y)

ax.annotate(n[0], (z[0], y[0]), xytext=(z[0]+0.05, y[0]+0.3), 
    arrowprops=dict(facecolor='red', shrink=0.05))

ax.annotate(n[1], (z[1], y[1]), xytext=(z[1]-0.05, y[1]-0.3), 
    arrowprops = dict(  arrowstyle="->",
                        connectionstyle="angle3,angleA=0,angleB=-90"))

ax.annotate(n[2], (z[2], y[2]), xytext=(z[2]-0.05, y[2]-0.3), 
    arrowprops = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1))

ax.annotate(n[3], (z[3], y[3]), xytext=(z[3]+0.05, y[3]-0.2), 
    arrowprops = dict(arrowstyle="fancy"))

ax.annotate(n[4], (z[4], y[4]), xytext=(z[4]-0.1, y[4]-0.2),
    bbox=dict(boxstyle="round", alpha=0.1), 
    arrowprops = dict(arrowstyle="simple"))

plt.show()

Sẽ tạo ra biểu đồ sau:

Hướng dẫn how do you label data points in a scatter plot in python? - làm thế nào để bạn gắn nhãn các điểm dữ liệu trong một biểu đồ phân tán trong python?

  1. Thêm nhãn vào các điểm biểu đồ phân tán bằng hàm matplotlib.pyplot.annotate()
  2. Thêm nhãn vào các điểm biểu đồ phân tán bằng hàm
    matplotlib.pyplot.annotate(text,
                               xy, 
                               *args, 
                               **kwargs)
    
    0

Để gắn nhãn các điểm biểu đồ phân tán trong matplotlib, chúng ta có thể sử dụng hàm matplotlib.pyplot.annotate(), thêm một chuỗi ở vị trí được chỉ định. Tương tự, chúng ta cũng có thể sử dụng hàm

matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)
0 để thêm nhãn văn bản vào các điểm phân tán.

Thêm nhãn vào các điểm biểu đồ phân tán bằng hàm matplotlib.pyplot.annotate()

matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)

Nó chú thích điểm

matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)
4 với giá trị của tham số
matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)
5.
matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)
4 đại diện cho một cặp tọa độ
matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)
7 của điểm cần chú thích.

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()

Output:

Hướng dẫn how do you label data points in a scatter plot in python? - làm thế nào để bạn gắn nhãn các điểm dữ liệu trong một biểu đồ phân tán trong python?

Nó tạo ra hai mảng ngẫu nhiên,

matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)
8 và
matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)
9, cho tọa độ X và tọa độ y tương ứng của các điểm, tương ứng. Chúng tôi có một danh sách gọi là
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()
0 có cùng độ dài với
matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)
8 và
matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)
9, chứa các nhãn cho mỗi điểm. Cuối cùng, chúng tôi lặp lại thông qua một vòng lặp và sử dụng phương thức
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()
3 để thêm nhãn cho mỗi điểm trong biểu đồ phân tán.

Thêm nhãn vào các điểm biểu đồ phân tán bằng hàm matplotlib.pyplot.annotate(text, xy, *args, **kwargs) 0

matplotlib.pyplot.text(x,
                       y,
                       s, 
                       fontdict=None,
                       **kwargs)

Ở đây,

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()
5 và
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()
6 đại diện cho các tọa độ nơi chúng ta cần đặt văn bản và
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()
7 là nội dung của văn bản cần được thêm vào.

Hàm thêm văn bản

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()
7 tại điểm được chỉ định bởi
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()
5 và
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()
6, trong đó
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()
5 đại diện cho tọa độ x của điểm và
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()
6 đại diện cho tọa độ y.

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.text(X[i], Y[i],label)

plt.show()

Output:

Hướng dẫn how do you label data points in a scatter plot in python? - làm thế nào để bạn gắn nhãn các điểm dữ liệu trong một biểu đồ phân tán trong python?

Nó lặp lại thông qua một vòng lặp và sử dụng phương thức

matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)
0 để thêm nhãn cho mỗi điểm trong biểu đồ phân tán.

Trong hướng dẫn này, bạn có thể tìm cách thêm nhãn văn bản vào một biểu đồ phân tán trong Python ?.Bạn sẽ tìm thấy các ví dụ về cách thêm nhãn cho tất cả các điểm hoặc chỉ cho một số trong số chúng.add text labels to a scatterplot in Python?. You will find examples on how to add labels for all points or only for some of them.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import figure
from matplotlib.lines import Line2D

df = pd.read_csv("https://raw.githubusercontent.com/softhints/dataplotplus/master/data/happyscore_income.csv")


ineq = df.income_inequality

ineq_min = min(ineq)
ineq_max = max(ineq)

norm_ineq = (ineq - ineq_min)/(ineq_max - ineq_min)
df['norm_ineq'] = norm_ineq


figure(num=None, figsize=(18, 16), dpi=100, facecolor='w', edgecolor='k')

plt.xlabel('Income')
plt.ylabel('Happy Score')

region = df.region.unique()
print(region[0])
df.region = df.region.replace('\'','')
print(region[0])

region_colors = {'Central and Eastern Europe':'red', 'Western Europe':'red',
                 'Sub-Saharan Africa':'green', 'Middle East and Northern Africa':'green',
                 'North America':'blue', 'Latin America and Caribbean':'blue',
                 'Southeastern Asia':'cyan', 'Southern Asia':'cyan', 'Eastern Asia':'cyan',
                 'Australia and New Zealand':'purple'}

print(region_colors['Central and Eastern Europe'])

for i,j in df.iterrows():
    reg_color = region_colors.get(j.region.replace('\'',''), 'black')
    plt.scatter(df.avg_income[i], df.happyScore[i], s=df.avg_income[i] / 10, alpha = 0.25, color=reg_color)


custom = [ Line2D([], [], marker='.', color=i, linestyle='None', markersize=25) for i in region_colors.values()]

plt.legend(custom, region_colors.keys(), fontsize=15)

[plt.text(x=row['avg_income'], y=row['happyScore'], s=row['country']) for k,row in df.iterrows() if 'Europe' in row.region]
plt.show()

result:

Hướng dẫn how do you label data points in a scatter plot in python? - làm thế nào để bạn gắn nhãn các điểm dữ liệu trong một biểu đồ phân tán trong python?

Thêm nhãn văn bản vào các điểm dữ liệu trong scatterplot

Việc bổ sung các nhãn vào mỗi hoặc tất cả các điểm dữ liệu xảy ra trong dòng này:

[plt.text(x=row['avg_income'], y=row['happyScore'], s=row['country']) for k,row in df.iterrows() if 'Europe' in row.region]

Chúng tôi đang sử dụng các toàn bộ danh sách của Python.Lặp qua tất cả các hàng của DataFrame gốc.

Chỉ thêm nhãn cho khu vực 'Châu Âu'.Đối với mỗi X và Y, chúng tôi đang lấy tên quốc gia và tạo danh sách mới dưới dạng:

[Text(2096.76, 4.35, 'Armenia'),
 Text(19457.04, 7.2, 'Austria'),
 Text(3381.600000000001, 5.2120000000000015, 'Azerbaijan'),
 Text(17168.505, 6.937, 'Belgium'),
 Text(5354.82, 4.218, 'Bulgaria'),
 Text(5453.933333333333, 5.813, 'Belarus'),

Nếu bạn muốn dán nhãn tất cả các điểm bạn cần xóa mệnh đề IF:

[plt.text(x=row['avg_income'], y=row['happyScore'], s=row['country']) for k,row in df.iterrows()]