본문 바로가기

Error and Solve

[코드] matplotlib에서 marker 마커로 scatter plot하기 / 성능 그래프 피겨 figure

반응형

 

 

 

1. 가장 간단한 matplotlib with scatter plot 

 

import matplotlib.pyplot as plt

# Example Data
x = [10, 20, 30, 40, 50, 60]
y = [10, 30, 20, 50, 70, 80]
labels = ['Method A', 'Method B', 'Method C', 'Method D', 'Method E', 'Method F']
categories = ['Classic', 'Machine Learning', 'Self-Supervised', 
              'Externally Guided', 'Externally Guided', 'Machine Learning']
colors = ['green', 'blue', 'orange', 'red', 'red', 'blue']
markers = ['^', '^', 's', '*', '*', 's']

# Plotting
plt.figure(figsize=(8, 6))

# Scatter Points (without legend assignment here)
for i in range(len(x)):
    plt.scatter(
        x[i], y[i], 
        c=colors[i], marker=markers[i], 
        s=100, alpha=0.7  # Add transparency with alpha
    )
    plt.text(x[i] + 1, y[i], labels[i], fontsize=9)  # Add labels

# Add Arrow
plt.annotate(
    'Our method',                  # Text label
    xy=(60, 80),                   # Arrowhead location
    xytext=(40, 70),               # Start of arrow (tail)
    arrowprops=dict(
        facecolor='black',         # Arrow color
        shrink=0.05,               # Shrink arrowhead
        width=1,                   # Arrow width
        headwidth=8,               # Arrowhead width
        headlength=10              # Arrowhead length
    ),
    fontsize=10,
    color='black'
)

# Custom Gridlines
plt.axhline(y=50, color='gray', linestyle='--', linewidth=0.5)
plt.axhline(y=30, color='gray', linestyle='--', linewidth=0.5)

# Fixing Legend with Unique Categories
unique_categories = {}  # Dictionary to hold unique categories and their style
for i, category in enumerate(categories):
    if category not in unique_categories:
        unique_categories[category] = (colors[i], markers[i])  # Store color and marker for each category

# Add a single legend for unique categories
for category, (color, marker) in unique_categories.items():
    plt.scatter([], [], label=category, c=color, marker=marker, s=100, alpha=0.7)

# Place Legend at Bottom
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, frameon=False)

# Axis Titles and Show
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Clustering Accuracy on ImageNet-Dogs')
plt.tight_layout()
plt.show()

 

 

matplotlib으로 만든 가장 간단한 scatter plot  

 

두 가지 성능지표로 압도하고 있는 our method를 소개하기 위해서 x, y 둘다 score라고 가정하면 저희 method의 성능을 한 눈에 볼 수 있게 됩니다. 

 

그리고 만약 method의 이름과 그 분류를 나누고 싶다면 labels와 더불어 categories까지 색깔로 구분 시 더 그 method간의 비교가 확실할 수 있습니다. 

 

 

 

 

2. marker 색깔 칠하기

import matplotlib.pyplot as plt

# Example Data
x = [10, 20, 30, 40, 50, 60]
y = [10, 30, 20, 50, 70, 80]
labels = ['Method A', 'Method B', 'Method C', 'Method D', 'Method E', 'Method F']
categories = ['Classic Clustering', 'Deep Clustering', 'Self-Supervised Clustering', 
              'Externally Guided Clustering', 'Externally Guided Clustering', 'Deep Clustering']
colors = ['green', 'blue', 'orange', 'red', 'red', 'blue']
markers = ['^', '^', 's', '*', '*', 's']

# Plotting
plt.figure(figsize=(8, 6))

# Scatter Points with edgecolor and facecolor
for i in range(len(x)):
    plt.scatter(
        x[i], y[i], 
        facecolors='none',  # Marker face color
        edgecolors=colors[i],    # Marker edge color
        marker=markers[i], 
        s=100, alpha=0.7  # Add transparency with alpha
    )
    plt.text(x[i] + 1, y[i], labels[i], fontsize=9)  # Add labels

# Add Arrow
plt.annotate(
    'Our method',                  # Text label
    xy=(60, 80),                   # Arrowhead location
    xytext=(40, 70),               # Start of arrow (tail)
    arrowprops=dict(
        facecolor='black',         # Arrow color
        shrink=0.05,               # Shrink arrowhead
        width=1,                   # Arrow width
        headwidth=8,               # Arrowhead width
        headlength=10              # Arrowhead length
    ),
    fontsize=10,
    color='black'
)

# Custom Gridlines
plt.axhline(y=50, color='gray', linestyle='--', linewidth=0.5)
plt.axhline(y=30, color='gray', linestyle='--', linewidth=0.5)

# Fixing Legend with Unique Categories
unique_categories = {}  # Dictionary to hold unique categories and their style
for i, category in enumerate(categories):
    if category not in unique_categories:
        unique_categories[category] = (colors[i], markers[i])  # Store color and marker for each category

# Add a single legend for unique categories
for category, (color, marker) in unique_categories.items():
    plt.scatter([], [], label=category, facecolors=color, edgecolors='black', marker=marker, s=100, alpha=0.7)

# Place Legend at Bottom
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, frameon=False)

# Axis Titles and Show
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Clustering Accuracy on ImageNet-Dogs')
plt.tight_layout()
plt.show()

 

 

 

Marker를 테두리만 지정하고 싶을 수 있습니다 

 

그런 경우 


# Scatter Points with edgecolor and facecolor
for i in range(len(x)):
    plt.scatter(
        x[i], y[i], 
        facecolors='none',  # Marker face color
        edgecolors=colors[i],    # Marker edge color
        marker=markers[i], 
        s=100, alpha=0.7  # Add transparency with alpha
    )
    plt.text(x[i] + 1, y[i], labels[i], fontsize=9)  # Add labels

 

위처럼 facecolors="none"을 지정하면 안은 transparent 투명해지고 edge color만 원하는 색으로 지정할 수 있습니다. 

 

 

 

 



3. Matplotlib의 markers

 

import matplotlib.pyplot as plt

# Example Data
x = [10, 20, 30, 40, 50, 60]
y = [10, 30, 20, 50, 70, 80]
labels = ['Method A', 'Method B', 'Method C', 'Method D', 'Method E', 'Method F']
colors = ['green', 'blue', 'orange', 'red', 'red', 'blue']
markers = ['^', 'v', 's', '*', 'p', 's']

# Plotting
plt.figure(figsize=(8, 6))

# Scatter Points with edgecolor and facecolor
for i in range(len(x)):
    plt.scatter(
        x[i], y[i], 
        facecolors='none',  # Marker face color
        edgecolors=colors[i],    # Marker edge color
        marker=markers[i], 
        s=100, alpha=0.7  # Add transparency with alpha
    )
    plt.text(x[i] + 1, y[i], labels[i], fontsize=9)  # Add labels

# Add Arrow
plt.annotate(
    'Our method',                  # Text label
    xy=(60, 80),                   # Arrowhead location
    xytext=(40, 70),               # Start of arrow (tail)
    arrowprops=dict(
        facecolor='black',         # Arrow color
        shrink=0.05,               # Shrink arrowhead
        width=1,                   # Arrow width
        headwidth=8,               # Arrowhead width
        headlength=10              # Arrowhead length
    ),
    fontsize=10,
    color='black'
)

# Custom Gridlines
plt.axhline(y=50, color='gray', linestyle='--', linewidth=0.5)
plt.axhline(y=30, color='gray', linestyle='--', linewidth=0.5)

# Axis Titles and Show
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Clustering Accuracy on ImageNet-Dogs')
plt.tight_layout()
plt.show()

 

 

카테고리 없이 모든 메소드를 마커만으로 구별하고 싶을수도 있습니다. 

 

 

markers = ['^', 'v', 's', '*', 'p', 's']

# Plotting
plt.figure(figsize=(8, 6))

# Scatter Points with edgecolor and facecolor
for i in range(len(x)):
    plt.scatter(
        x[i], y[i], 
        facecolors='none',  # Marker face color
        edgecolors=colors[i],    # Marker edge color
        marker=markers[i], 
        s=100, alpha=0.7  # Add transparency with alpha
    )
    plt.text(x[i] + 1, y[i], labels[i], fontsize=9)  # Add labels

 

그런 경우 markers=[] 에서  각기 다른 모양으로 method를 지정해주고, 

plt.scatter 시 marker = markers[i]로 지정해주면 됩니다. 

 

 

 

matplotlib 공식 문서에서 지원하는 

마커의 종류를 볼 수 있습니다. 

 

 

 

 

 

 

이렇게 있습니다. 

 

https://matplotlib.org/stable/api/markers_api.html

 

matplotlib.markers — Matplotlib 3.9.3 documentation

matplotlib.markers Functions to handle markers; used by the marker functionality of plot, scatter, and errorbar. All possible markers are defined here: Note that special symbols can be defined via the STIX math font, e.g. "$\u266B$". For an overview over t

matplotlib.org

 

 

 

 

 

반응형