[파이썬] Seaborn 텍스트 추가

Seaborn is a popular data visualization library in Python. It is built on top of Matplotlib and provides a high-level interface for creating beautiful and informative graphics. In this blog post, we will explore how to add text to our Seaborn plots, which can be useful for annotating important points or providing additional information.

Adding Text with Annotations

Seaborn provides a convenient function called annotate() to add text to our plots. This function takes in the x and y coordinates where we want to place the text, as well as the text itself.

Here’s an example of how to use the annotate() function to add text to a Seaborn plot:

import seaborn as sns
import matplotlib.pyplot as plt

# Create a scatter plot using Seaborn
sns.scatterplot(x='x', y='y', data=data)

# Add text annotation at coordinates (2, 5)
plt.annotate('Important point', xy=(2, 5), xytext=(3, 7),
             arrowprops=dict(facecolor='black', arrowstyle='->'))

# Show the plot
plt.show()

In this example, we first create a scatter plot using Seaborn’s scatterplot() function. We then use the annotate() function to add the text “Important point” at the coordinates (2, 5). The xytext parameter specifies the coordinates of the text’s offset, i.e., where the text label itself should be placed. We also provide arrowprops to draw an arrow pointing from the annotation to the text.

Customizing Text Appearance

We can customize the appearance of the text by modifying the arrowprops and textcoords parameters of the annotate() function. For example, we can change the font size, font color, and font style of the text.

Here’s an example of how to customize the text appearance in a Seaborn plot:

import seaborn as sns
import matplotlib.pyplot as plt

# Create a scatter plot using Seaborn
sns.scatterplot(x='x', y='y', data=data)

# Add text annotation at coordinates (2, 5) with custom appearance
plt.annotate('Important point', xy=(2, 5), xytext=(3, 7),
             arrowprops=dict(facecolor='black', arrowstyle='->'),
             fontsize=12, color='red', style='italic')

# Show the plot
plt.show()

In this example, we add the parameters fontsize=12 to change the font size of the text to 12 points, color='red' to change the font color to red, and style='italic' to change the font style to italic.

Conclusion

Adding text to Seaborn plots can be done using the annotate() function, which provides flexibility in placing and customizing the appearance of the text. By effectively annotating our plots, we can highlight important points or provide additional information to enhance the understanding of our data visualizations.