Supercharge Your Charts

Essential Matplotlib Customisations for Beginners

Customising Charts with Matplotlib: Fun and Interesting Examples

Sponsored
AiNexaVerse NewsWeekly AI Tools in your email!

Welcome back to our series on data visualisation with Matplotlib! In this post, we'll dive deeper into customising charts to make your visualisations not only informative but also visually appealing. We'll use fun and interesting real-life examples to show you how to tweak your charts for maximum impact.

Why Customise Your Charts?

Customising your charts helps in:

  • Making them more readable and attractive.

  • Highlighting specific data points or trends.

  • Tailoring the visualisation to your audience's preferences.

 

Getting Started with Customisation

Example 1: Customising a Line Chart

Let's start with a line chart showing the average temperature over a week. We'll customise the line style, markers, and colors.

 

import matplotlib.pyplot as plt

# Data

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

temperatures = [22, 21, 23, 20, 24, 26, 27]

 

# Create a simple line chart with customisations

plt.plot(days, temperatures, label='Temperature', color='blue', linestyle='--', marker='o')

 

# Add title and labels

plt.title('Average Temperature Over a Week')

plt.xlabel('Days')

plt.ylabel('Temperature (°C)')

 

# Customise the grid

plt.grid(True, which='both', linestyle='--', linewidth=0.5)

 

# Add legend

plt.legend()

 

# Display the chart

plt.show()

 

Explanation:

plt.plot(): Creates a line chart.

  •  days: Data for the x-axis (days of the week).

  •  temperatures: Data for the y-axis (temperatures in °C).

  •  label='Temperature': Adds a label for the line (useful for the legend).

  •  color='blue': Sets the color of the line to blue.

  •  linestyle='--': Sets the line style to dashed.

  •  marker='o': Adds circular markers at each data point.

 

plt.title(): Adds a title to the chart.

plt.xlabel(): Adds a label to the x-axis.

plt.ylabel(): Adds a label to the y-axis.

plt.grid(): Adds a grid to the chart.

  •  True: Enables the grid.

  •  which='both': Applies the grid to both major and minor ticks.

  •  linestyle='--': Sets the grid line style to dashed.

  •  linewidth=0.5: Sets the grid line width.

plt.legend(): Displays the legend.

Line Chart

Example 2: Customising a Bar Chart

Now, let's create a bar chart showing the sales of different ice cream flavors. We'll customise the bar colors, add a grid, and rotate the x-axis labels for better readability.

 

import matplotlib.pyplot as plt

# Data

flavors = ['Vanilla', 'Chocolate', 'Strawberry', 'Mint', 'Cookie Dough']

sales = [150, 200, 100, 75, 125]

 

# Create a bar chart with customisations

plt.bar(flavors, sales, color=['#FFDDC1', '#D4A5A5', '#FFC1C1', '#A0D4A0', '#C1D4FF'])

 

# Add title and labels

plt.title('Ice Cream Sales by Flavor')

plt.xlabel('Flavors')

plt.ylabel('Sales (Units)')

 

# Customise the grid

plt.grid(axis='y', linestyle='--', linewidth=0.5)

 

# Rotate x-axis labels

plt.xticks(rotation=45)

 

# Display the chart

plt.show()

 

Explanation:

plt.bar(): Creates a bar chart.

  •  flavors: Data for the x-axis (ice cream flavors).

  •  sales: Data for the y-axis (number of units sold).

  •  color: Sets the colors of the bars using hex color codes.

 

plt.grid(): Adds a grid to the chart.

  •  axis='y': Adds the grid only to the y-axis.

  •  linestyle='--': Sets the grid line style to dashed.

  •  linewidth=0.5: Sets the grid line width.

 

plt.xticks(): Rotates the x-axis labels for better readability.

  • rotation=45: Rotates the labels by 45 degrees.

Bar Chart

Example 3: Customising a Scatter Plot

Let's create a scatter plot showing the heights and weights of a group of people. We'll customise the marker size and color based on a third variable, age.

 

import matplotlib.pyplot as plt

# Data

heights = [150, 160, 170, 180, 190, 200]

weights = [50, 60, 70, 80, 90, 100]

ages = [15, 25, 35, 45, 55, 65]

 

# Create a scatter plot with customisations

scatter = plt.scatter(heights, weights, c=ages, s=ages, cmap='viridis', alpha=0.6, edgecolors='w', linewidth=0.5)

 

# Add title and labels

plt.title('Height vs Weight with Age')

plt.xlabel('Height (cm)')

plt.ylabel('Weight (kg)')

 

# Add a color bar

cbar = plt.colorbar(scatter)

cbar.set_label('Age')

 

# Display the chart

plt.show()

Explanation:

plt.scatter(): Creates a scatter plot.

  •  heights: Data for the x-axis (heights in cm).

  •  weights: Data for the y-axis (weights in kg).

  •  c=ages: Sets the colors of the markers based on the ages data.

  •  s=ages: Sets the sizes of the markers based on the ages data.

  •  cmap='viridis': Sets the color map to 'viridis' (a color gradient).

  •  alpha=0.6: Sets the transparency level of the markers.

  •  edgecolors='w': Sets the edge color of the markers to white.

  •  linewidth=0.5: Sets the width of the marker edges.

 

plt.colorbar(): Adds a color bar to the chart.

  •  scatter: The scatter plot object to which the color bar applies.

  •  set_label(): Adds a label to the color bar.

Scatter Plot

Example 4: Customising a Histogram

Let's create a histogram showing the distribution of exam scores. We'll customise the bins, colors, and add annotations.

 

import matplotlib.pyplot as plt

# Data

scores = [56, 78, 45, 89, 90, 62, 74, 88, 93, 55, 69, 80, 81, 77, 68]

 

# Create a histogram with customisations

plt.hist(scores, bins=8, color='skyblue', edgecolor='black', alpha=0.7)

 

# Add title and labels

plt.title('Distribution of Exam Scores')

plt.xlabel('Scores')

plt.ylabel('Frequency')

 

# Add annotations

plt.annotate('Highest Score', xy=(90, 2), xytext=(70, 3),

             arrowprops=dict(facecolor='black', shrink=0.05))

 

# Display the chart

plt.show()

 

Explanation:

plt.hist(): Creates a histogram.

  • scores: Data to be plotted.

  • bins=8: Number of bins (intervals) in the histogram.

  • color='skyblue': Sets the color of the bars.

  • edgecolor='black': Sets the color of the bar edges.

  • alpha=0.7: Sets the transparency level of the bars.

 pltannotate(): Adds an annotation to the chart.

  • 'Highest Score': Text of the annotation.

  • xy=(90, 2): Coordinates of the point to annotate.

  • xytext=(70, 3): Coordinates of the annotation text.

  • arrowprops=dict(facecolor='black', shrink=0.05): Properties of the annotation arrow.

Histogram

Example 5: Customising a Pie Chart

Lastly, let's create a pie chart showing the market share of different smartphone brands. We'll customise the colors, add a shadow, and explode a slice.

 

import matplotlib.pyplot as plt

# Data

brands = ['Brand A', 'Brand B', 'Brand C', 'Brand D']

market_share = [35, 30, 20, 15]

colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']

 

# Create a pie chart with customizations

plt.pie(market_share, labels=brands, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140,

        explode=(0.1, 0, 0, 0))

 

# Add title

plt.title('Smartphone Market Share')

 

# Display the chart

plt.show()

 

Explanation:

plt.pie(): Creates a pie chart.

  • market_share: Data for the pie slices.

  • labels=brands: Labels for each slice.

  • colors: Colors for each slice.

  • autopct='%1.1f%%': Displays the percentage of each slice.

  • shadow=True: Adds a shadow to the pie chart.

  • startangle=140: Starts the first slice at 140 degrees.

  • explode=(0.1, 0, 0, 0): Offsets the first slice for emphasis.

Pie Chart

Conclusion

Customising your charts can make a significant difference in how your data is perceived and understood. Matplotlib provides a wealth of options to tailor your visualisations to your specific needs. Whether you're highlighting key data points, making your charts more readable, or simply adding some flair, these customisation techniques will help you create effective and engaging visualizations.

Sponsored
AiNexaVerse NewsWeekly AI Tools in your email!

Ready to Take Your Visualisations to the Next Level?

Subscribe to our newsletter now and get a free Python cheat sheet! Dive deeper into Python programming with more exciting projects and tutorials designed just for beginners.

Keep exploring, keep coding, and enjoy your journey into data visualisation with Matplotlib!