[파이썬] ggplot 기본 테마 변경하기

ggplot is a widely used plotting library in Python for creating beautiful and informative data visualizations. One of the great features of ggplot is the ability to customize the visual appearance of plots by changing the default theme.

In this blog post, we will explore how to change the default theme of ggplot in Python. Let’s get started!

Step 1: Installing the necessary packages

Before we begin, make sure you have ggplot and matplotlib installed in your Python environment. If not, you can install them using pip:

pip install ggplot matplotlib

Step 2: Importing the required libraries

To start, we need to import the necessary libraries:

from ggplot import *
import matplotlib.pyplot as plt

Step 3: Changing the default theme

To change the default theme, we can use the theme_set() function provided by ggplot. This function allows us to set the default theme to any of the built-in themes provided by ggplot, or even to a custom theme.

theme_set(theme_bw())

In the above example, we are using the theme_bw() function to set the default theme to a classic black and white theme.

Step 4: Creating a plot

Now that we have set the default theme, let’s create a simple scatter plot to see the changes in action.

df = pd.DataFrame({'x': range(10), 'y': range(10)})
ggplot(df, aes(x='x', y='y')) + \
    geom_point() + \
    xlab('X') + \
    ylab('Y') + \
    ggtitle('Scatter Plot')

Step 5: Customizing the plot

With the default theme set, we can further customize our plot using the available options provided by ggplot. For example, we can change the color palette, the font size, or add grid lines.

ggplot(df, aes(x='x', y='y')) + \
    geom_point() + \
    xlab('X') + \
    ylab('Y') + \
    ggtitle('Scatter Plot') + \
    theme(text=element_text(size=12),
          panel_grid_major=element_line(color='gray'),
          panel_background=element_rect(color='white', fill='white'))

In the above example, we are customizing the font size to 12, adding gray grid lines, and setting a white background color for the plot.

Step 6: Saving the plot

Finally, once we are satisfied with the customized plot, we can save it to a file using the save() function provided by ggplot.

g = ggplot(df, aes(x='x', y='y')) + \
    geom_point() + \
    xlab('X') + \
    ylab('Y') + \
    ggtitle('Scatter Plot') + \
    theme(text=element_text(size=12),
          panel_grid_major=element_line(color='gray'),
          panel_background=element_rect(color='white', fill='white'))

g.save("scatter_plot.png")

The above code will save the plot as a PNG image file named scatter_plot.png in the same directory as the script.

Conclusion

In this blog post, we have learned how to change the default theme of ggplot in Python. By customizing the theme, we can create visually appealing and informative data visualizations. Feel free to experiment with different themes and customization options to make your plots stand out.

Happy plotting!