Updated On : Mar-22,2023 Time Investment : ~15 mins

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

Matplotlib is a widely used plotting library in Python for creating high-quality visualizations for data analysis and presentation.

While Matplotlib offers a wide range of customization options to create visually appealing and informative plots, its default styling may not always be suitable for every use case. In such cases, it is useful to change the theme or style of Matplotlib charts to enhance their appearance and readability.

The Matplotlib library includes several predefined styles, such as "classic", "ggplot", "seaborn", and "fivethirtyeight", that can be easily applied to charts. These styles are designed to provide a consistent look and feel across all elements of the chart, including colors, fonts, and backgrounds.

What Can You Learn From This Article?

In this tutorial, we have explained how to apply predefined styles to "Matplotlib charts" using the "plt.style.use()" and "plt.style.context()" functions. With these functions, users can enhance the visual appeal and readability of their Matplotlib charts and create stunning visualizations for data analysis and presentation.

By the end of this tutorial, readers will have a better understanding of how to customize the appearance of Matplotlib charts to make them more visually appealing and effective at conveying the information in the data. They will also have a good grasp of the different styles and themes available in Matplotlib and how to use them to create charts that meet their specific needs. Whether you are a data analyst, data scientist, or just someone interested in data visualization, this article will provide you with valuable insights into how to style Matplotlib charts.

Video Tutorial

Please feel free to check below video tutorial if feel comfortable learning through videos.


First, we have imported matplotlib and printed the version that we have used in our tutorial.

import matplotlib

print("Matplotlib Version : {}".format(matplotlib.__version__))
Matplotlib Version : 3.5.3

Load Dataset

In this section, we have loaded a wine dataset available from Python ML library scikit-learn. The dataset has measurements of various ingredients used to prepare 3 different types of wine. We have loaded dataset as pandas dataframe.

After loading dataset as dataframe, we have grouped entries by wine type and calculated average values of ingredients per wine type in the next cell. It's another dataframe that we'll use to create charts.

import pandas as pd
from sklearn.datasets import load_wine

wine  = load_wine()

print("Dataset Size : ", wine.data.shape)

wine_df = pd.DataFrame(data=wine.data, columns=wine.feature_names)
wine_df["WineType"] = [wine.target_names[typ] for typ in wine.target]

wine_df.head()
Dataset Size :  (178, 13)
alcohol malic_acid ash alcalinity_of_ash magnesium total_phenols flavanoids nonflavanoid_phenols proanthocyanins color_intensity hue od280/od315_of_diluted_wines proline WineType
0 14.23 1.71 2.43 15.6 127.0 2.80 3.06 0.28 2.29 5.64 1.04 3.92 1065.0 class_0
1 13.20 1.78 2.14 11.2 100.0 2.65 2.76 0.26 1.28 4.38 1.05 3.40 1050.0 class_0
2 13.16 2.36 2.67 18.6 101.0 2.80 3.24 0.30 2.81 5.68 1.03 3.17 1185.0 class_0
3 14.37 1.95 2.50 16.8 113.0 3.85 3.49 0.24 2.18 7.80 0.86 3.45 1480.0 class_0
4 13.24 2.59 2.87 21.0 118.0 2.80 2.69 0.39 1.82 4.32 1.04 2.93 735.0 class_0
avg_wine_df = wine_df.groupby("WineType").mean().reset_index()

avg_wine_df
WineType alcohol malic_acid ash alcalinity_of_ash magnesium total_phenols flavanoids nonflavanoid_phenols proanthocyanins color_intensity hue od280/od315_of_diluted_wines proline
0 class_0 13.744746 2.010678 2.455593 17.037288 106.338983 2.840169 2.982373 0.290000 1.899322 5.528305 1.062034 3.157797 1115.711864
1 class_1 12.278732 1.932676 2.244789 20.238028 94.549296 2.258873 2.080845 0.363662 1.630282 3.086620 1.056282 2.785352 519.507042
2 class_2 13.153750 3.333750 2.437083 21.416667 99.312500 1.678750 0.781458 0.447500 1.153542 7.396250 0.682708 1.683542 629.895833

1. Set Style Permanently for All Matplotlib Charts

In this section, we have first created charts without any themes. Then, we have explained how to introduce themes to charts to improve their look.

1.1 Scatter Chart

The below code creates a simple scatter chart showing the relationship between ingredients "alcohol" and "malic_acid" of our wine dataset.

The code starts by creating a new figure with the plt.figure() function and sets the size of the figure using the figsize parameter. In this case, the size of the figure is set to 10 inches by 7 inches.

Then, the code creates a scatter plot using the plt.scatter() function. The scatter plot is created using two variables from the wine_df DataFrame, namely alcohol and malic_acid. The x and y parameters of the scatter() function correspond to these two variables respectively.

Next, the code sets the labels of the x-axis and y-axis using the plt.xlabel() and plt.ylabel() functions respectively.

Then, the code sets the limits of the x-axis and y-axis using the plt.xlim() and plt.ylim() functions respectively.

Next, the code sets the tick labels of the x-axis and y-axis using the plt.xticks() and plt.yticks() functions respectively. The ticks parameter specifies the positions of the ticks and the labels parameter specifies the labels of the ticks.

Finally, the code sets the title of the plot using the plt.title() function and displays the plot using the plt.show() function.

import matplotlib.pyplot as plt

plt.figure(figsize=(10,7))

plt.scatter(x=wine_df["alcohol"], y=wine_df["malic_acid"],)

plt.xlabel("Alcohol")
plt.ylabel("Malic Acid")

plt.xlim(10,16)
plt.ylim(0, 7)

plt.xticks(ticks=range(10,17), labels=range(10,17))
plt.yticks(ticks=range(0,8), labels=range(0,8))

plt.title("Alcohol vs Malic Acid")

plt.show()

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

1.2 Grouped Bar Chart

The code creates a grouped bar chart of the average values of five wine ingredients for each type of wine.

The list ingredients contains the names of the five ingredients to be plotted.

The avg_wine_df DataFrame contains the average values of these five ingredients for each type of wine.

The plot.bar() function creates a bar chart with x and y parameters. Here, the x parameter is set to "WineType", which specifies the column in avg_wine_df that contains the type of wine, and the y parameter is set to ingredients, which specifies the list of ingredient columns to be plotted.

The function also takes additional parameters such as xlabel, ylabel, title, and figsize which set the x-axis label, y-axis label, the title of the plot, and the size of the figure respectively.

In this case, the x-axis label is set to "Wine Type", the y-axis label is set to "Avg. Ingredients", the title of the plot is set to "Average Ingredients Per Wine Type", and the size of the figure is set to 12 inches by 6 inches using the figsize parameter.

ingredients = ["malic_acid", "ash", "total_phenols", "flavanoids", "proanthocyanins"]

avg_wine_df.plot.bar(x="WineType", y=ingredients,
                     xlabel="Wine Type", ylabel="Avg. Ingredients",
                     title="Average Ingredients Per Wine Type",
                     figsize=(12,6)
                    );

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

1.3 Stacked Bar Chart

The below code creates a stacked bar chart of the average values of five wine ingredients for each type of wine.

ingredients = ["malic_acid", "ash", "total_phenols", "flavanoids", "proanthocyanins"]

avg_wine_df.plot.bar(x="WineType", y=ingredients, stacked=True,
                     xlabel="Wine Type", ylabel="Avg. Ingredients",
                     title="Average Ingredients Per Wine Type",
                     figsize=(10,6)
                    );

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

We can notice from the output that all three charts created till now had default theme which has simple white background and same font size for all text in the chart. There is no grid. Let's improve the look by adding a theme using just one line of code.

1.4 Styled Charts

The below line of code sets the plotting style of Matplotlib to "seaborn".

Matplotlib provides several plotting styles to choose from, each with a distinct look and feel. The default style is "classic", but other options include "ggplot", "dark_background", "bmh", "seaborn", and more.

The plt.style.use() function is used to set the plot style. Here, seaborn is the style being used. Seaborn is a popular plotting library built on top of Matplotlib and provides a set of customized themes and color palettes for creating attractive statistical graphics.

Once the style is set using this code, all subsequent plots created using Matplotlib will use the specified style until another style is set.

After setting the style, we have again executed our scatter chart creation code and we can see how it has improved the look of the chart.

plt.style.use("seaborn");
import matplotlib.pyplot as plt

plt.figure(figsize=(10,7))

plt.scatter(x=wine_df["alcohol"], y=wine_df["malic_acid"],)

plt.xlabel("Alcohol")
plt.ylabel("Malic Acid")

plt.xlim(10,16)
plt.ylim(0, 7)

plt.xticks(ticks=range(10,17), labels=range(10,17))
plt.yticks(ticks=range(0,8), labels=range(0,8))

plt.title("Alcohol vs Malic Acid")

plt.show()

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

We can retrieve a list of available styles by calling available attribute from plt.style module.

print("List of Available Styles : {}".format(plt.style.available))
List of Available Styles : ['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']

The below code sets the plotting style of Matplotlib to "fivethirtyeight". This style is designed to mimic the style of plots and visualizations used by the news website FiveThirtyEight. The style is characterized by bold lines, large fonts, and a distinctive color scheme.

plt.style.use("fivethirtyeight");

After setting the theme, we have re-executed the code of all 3 charts that we had created earlier and we can notice how the look of the charts is improved.

import matplotlib.pyplot as plt

plt.figure(figsize=(10,7))

plt.scatter(x=wine_df["alcohol"], y=wine_df["malic_acid"],)

plt.xlabel("Alcohol")
plt.ylabel("Malic Acid")

plt.xlim(10,16)
plt.ylim(0, 7)

plt.xticks(ticks=range(10,17), labels=range(10,17))
plt.yticks(ticks=range(0,8), labels=range(0,8))

plt.title("Alcohol vs Malic Acid")

plt.show()

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

ingredients = ["malic_acid", "ash", "total_phenols", "flavanoids", "proanthocyanins"]

avg_wine_df.plot.bar(x="WineType", y=ingredients,
                     xlabel="Wine Type", ylabel="Avg. Ingredients",
                     title="Average Ingredients Per Wine Type",
                     figsize=(12,6)
                    );

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

ingredients = ["malic_acid", "ash", "total_phenols", "flavanoids", "proanthocyanins"]

avg_wine_df.plot.bar(x="WineType", y=ingredients, stacked=True,
                     xlabel="Wine Type", ylabel="Avg. Ingredients",
                     title="Average Ingredients Per Wine Type",
                     figsize=(10,6)
                    );

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

2. Use Style as a Context Manager

In this section, we have explained how to set a theme temporary for one chart using context manager.

The with plt.style.context("ggplot") line temporarily sets the Matplotlib style to "ggplot" within the indented code block that follows.

This is an alternative way of setting the style for a specific plot, rather than using plt.style.use("ggplot") to set it globally.

with plt.style.context("ggplot"):
    import matplotlib.pyplot as plt

    plt.figure(figsize=(10,7))

    plt.scatter(x=wine_df["alcohol"], y=wine_df["malic_acid"],)

    plt.xlabel("Alcohol")
    plt.ylabel("Malic Acid")

    plt.xlim(10,16)
    plt.ylim(0, 7)

    plt.xticks(ticks=range(10,17), labels=range(10,17))
    plt.yticks(ticks=range(0,8), labels=range(0,8))

    plt.title("Alcohol vs Malic Acid")

    plt.show()

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

As you can see below, outside of context, again fivethirtyeight theme is applied.

import matplotlib.pyplot as plt

plt.figure(figsize=(10,7))

plt.scatter(x=wine_df["alcohol"], y=wine_df["malic_acid"],)

plt.xlabel("Alcohol")
plt.ylabel("Malic Acid")

plt.xlim(10,16)
plt.ylim(0, 7)

plt.xticks(ticks=range(10,17), labels=range(10,17))
plt.yticks(ticks=range(0,8), labels=range(0,8))

plt.title("Alcohol vs Malic Acid")

plt.show()

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

Below, we have applied ggplot theme to our grouped bar chart.

ingredients = ["malic_acid", "ash", "total_phenols", "flavanoids", "proanthocyanins"]

with plt.style.context("ggplot"):
    avg_wine_df.plot.bar(x="WineType", y=ingredients,
                         xlabel="Wine Type", ylabel="Avg. Ingredients",
                         title="Average Ingredients Per Wine Type",
                         figsize=(12,6)
                        );

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

Below, we have applied ggplot theme to our stacked bar chart.

ingredients = ["malic_acid", "ash", "total_phenols", "flavanoids", "proanthocyanins"]

with plt.style.context("ggplot"):
    avg_wine_df.plot.bar(x="WineType", y=ingredients, stacked=True,
                         xlabel="Wine Type", ylabel="Avg. Ingredients",
                         title="Average Ingredients Per Wine Type",
                         figsize=(10,6)
                        );

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

ingredients = ["malic_acid", "ash", "total_phenols", "flavanoids", "proanthocyanins"]

with plt.style.context("seaborn"):
    avg_wine_df.plot.bar(x="WineType", y=ingredients,
                         xlabel="Wine Type", ylabel="Avg. Ingredients",
                         title="Average Ingredients Per Wine Type",
                         figsize=(12,6)
                        );

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

Below, we have applied seaborn theme to our stacked bar chart.

ingredients = ["malic_acid", "ash", "total_phenols", "flavanoids", "proanthocyanins"]

with plt.style.context("seaborn"):
    avg_wine_df.plot.bar(x="WineType", y=ingredients, stacked=True,
                         xlabel="Wine Type", ylabel="Avg. Ingredients",
                         title="Average Ingredients Per Wine Type",
                         figsize=(10,6)
                        );

Style Matplotlib Charts | Change Theme of Matplotlib Charts | Python

We discussed two different ways of changing the style of matplotlib charts.

  1. plt.style.use() - Set style permanently for charts.
  2. plt.style.context() - Set style for a particular context.

References

Sunny Solanki  Sunny Solanki

YouTube Subscribe Comfortable Learning through Video Tutorials?

If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.

Need Help Stuck Somewhere? Need Help with Coding? Have Doubts About the Topic/Code?

When going through coding examples, it's quite common to have doubts and errors.

If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.

You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.

Share Views Want to Share Your Views? Have Any Suggestions?

If you want to

  • provide some suggestions on topic
  • share your views
  • include some details in tutorial
  • suggest some new topics on which we should create tutorials/blogs
Please feel free to contact us at coderzcolumn07@gmail.com. We appreciate and value your feedbacks. You can also support us with a small contribution by clicking DONATE.