[파이썬] seaborn 다중 패싯 그리드(FacetGrid)

Seaborn is a popular data visualization library for Python that provides a high-level interface to create beautiful and informative statistical graphics. One of its powerful features is the ability to create multiple facets or subplots in a grid using the FacetGrid class.

The FacetGrid class allows us to visualize relationships between multiple variables by creating a grid of subplots based on the unique levels of one or more categorical variables. Each subplot in the grid represents a specific level or combination of levels of the categorical variables.

Let’s dive into an example to see how we can use FacetGrid in Seaborn.

Example

Assume we have a dataset that contains information about different car models, including their prices, horsepower, and fuel efficiency. We want to explore the relationship between the price and horsepower, and the price and fuel efficiency, while considering the car’s origin (American, European, or Asian).

Here’s how we can use FacetGrid to create a multiple-facet grid:

import seaborn as sns

# Load the dataset
car_data = sns.load_dataset("mpg")

# Create a FacetGrid with two variables: origin and horsepower
g = sns.FacetGrid(car_data, col="origin")
g.map(sns.scatterplot, "horsepower", "price")

# Create another FacetGrid with two variables: origin and mpg
g = sns.FacetGrid(car_data, col="origin")
g.map(sns.scatterplot, "mpg", "price")

# Display the plot
snsplt.show()

In the above code, we first load a dataset using the sns.load_dataset function. Then, we create two instances of FacetGrid. In the first FacetGrid, we specify the variable "origin" as the column variable, and in the second FacetGrid, we specify "origin" as the column variable again.

We use the map function to specify the plot type we want to create for each subplot. In this example, we use sns.scatterplot to create scatter plots for both relationships: horsepower vs. price and mpg vs. price.

Finally, we display the plot using snsplt.show().

The resulting plot will show multiple subplots, each representing a different level of the origin variable. This allows us to compare the relationships between price and horsepower, and price and fuel efficiency for each car origin separately.

Seaborn’s FacetGrid provides a flexible and convenient way to explore relationships between multiple variables in a dataset. By creating subplots in a grid, we can analyze and understand the data more effectively.