Matplotlib is the most commonly used package for plotting in Python¶

1. A simple line chart in Python¶

In [ ]:
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(3,2), facecolor='white')  # Size, Background color
# The fig here is a handle of the figure. It can be used to make some adjustment
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

2. Add x-Label and y-Label to the figure¶

In [ ]:
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]

fig = plt.figure(figsize=(3,2), facecolor='white')
plt.plot(x, y)
plt.title('Simple Line Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

3. Select a plotting style supported in matplotlib¶

In [ ]:
plt.style.use('seaborn-v0_8-paper') # this just need to set once.
fig = plt.figure(figsize=(3,2), facecolor='white')
plt.plot(x, y, 'o-', color='black')
plt.title('Styled Line Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

3.1 Show all supported styles in matplotlib¶

In [ ]:
import pandas as pd
allStyles = plt.style.available
# Convert to dataframe for better visualization.
allstyles_df = pd.DataFrame(allStyles, columns=['Style'])
allstyles_df
Out[ ]:
Style
0 Solarize_Light2
1 _classic_test_patch
2 _mpl-gallery
3 _mpl-gallery-nogrid
4 bmh
5 classic
6 dark_background
7 fast
8 fivethirtyeight
9 ggplot
10 grayscale
11 seaborn-v0_8
12 seaborn-v0_8-bright
13 seaborn-v0_8-colorblind
14 seaborn-v0_8-dark
15 seaborn-v0_8-dark-palette
16 seaborn-v0_8-darkgrid
17 seaborn-v0_8-deep
18 seaborn-v0_8-muted
19 seaborn-v0_8-notebook
20 seaborn-v0_8-paper
21 seaborn-v0_8-pastel
22 seaborn-v0_8-poster
23 seaborn-v0_8-talk
24 seaborn-v0_8-ticks
25 seaborn-v0_8-white
26 seaborn-v0_8-whitegrid
27 tableau-colorblind10

4. Choose different markers and line styles¶

In [ ]:
fig = plt.figure(figsize=(3,2), facecolor='white')
plt.plot(x, y, '*--', color='red', markersize=10) # see 4.1 for more details about markers and line styles
plt.title('Styled Line Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

4.1 Markers and line styles in plot¶

1. Line Style¶

The second part of the shorthand 'o-' represents the line style. Some common line styles include:¶

'-': Solid line
'--': Dashed line
'-.': Dash-dot line
':': Dotted line
'': No line (used to only show markers)

2. Markers¶

The first part, 'o', is the marker symbol. matplotlib supports many types of markers:¶

'o': Circle marker
'.': Point marker
',': Pixel marker
'x': X marker
'+': Plus marker
'v': Triangle down marker
'^': Triangle up marker
'<': Triangle left marker
'>': Triangle right marker
's': Square marker
'p': Pentagon marker
'*': Star marker
'h': Hexagon1 marker
'H': Hexagon2 marker
'D': Diamond marker
'd': Thin diamond marker
'|': Vertical line marker
'_': Horizontal line marker

5. Set range of x and y axis¶

In [ ]:
fig = plt.figure(figsize=(3,2), facecolor='white')
plt.plot(x, y, '*--', color='red', markersize=10)
plt.xlim(0, 6)  # Set the range from 0 to 6
plt.ylim(0, 50)  # Set the range from 0 to 50
plt.title('Styled Line Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

6. Change fontsize for the whole figure¶

In [ ]:
# Update the default font size for the entire figure
# This line need to write before making a plot

# Set the seaborn style to classic.
# Using "seaborn-v0_8-paper" will override the setting of fontsize
plt.style.use('classic')

# Update the font size after setting the style
plt.rcParams.update({'font.size': 14})

fig = plt.figure(figsize=(3,2), facecolor='white')

plt.plot(x, y, 'o-', color='black', markersize=6)
plt.xlim(0, 6)  # Set the range from 0 to 6
plt.ylim(0, 50)  # Set the range from 0 to 50
plt.title('Styled Line Plot')
plt.xlabel('Distance (m)') # using meaningful label will make it more clear
plt.ylabel('Height (m)')
plt.show()

7. set tick width to 2¶

In [ ]:
plt.style.use('classic')
plt.rcParams.update({'font.size': 14})
fig = plt.figure(figsize=(3,2), facecolor='white')
plt.plot(x, y, 'o-', color='black', markersize=6)
plt.xlim(0, 6)  # Set the range from 0 to 6
plt.ylim(0, 50)  # Set the range from 0 to 50
plt.title('Styled Line Plot')
plt.xlabel('Distance (m)') # using meaningful label will make it more clear
plt.ylabel('Height (m)')

# Set tick parameters
plt.tick_params(width=2)  # Set tick width to 2
plt.show()

8. Add grids in the plot¶

In [ ]:
plt.style.use('classic')
plt.rcParams.update({'font.size': 14})
fig = plt.figure(figsize=(3,2), facecolor='white')
plt.plot(x, y, 'o-', color='black', markersize=6)
plt.xlim(0, 6)  # Set the range from 0 to 6
plt.ylim(0, 50)  # Set the range from 0 to 50
plt.title('Styled Line Plot')
plt.xlabel('Distance (m)') # using meaningful label will make it more clear
plt.ylabel('Height (m)')
plt.tick_params(width=2)  # Set tick width to 2
# Add grids
plt.grid(which='both', linestyle=':', linewidth=0.7, color='gray')  # You can customize these parameters

plt.show()

In matplotlib, you can specify colors in various ways. Here are the most common methods for setting colors along with their options:¶

1. Basic Color Names¶

You can use standard color names (e.g., 'red', 'blue', 'green', etc.). Here’s a list of some commonly used color names:¶

'red'
'green'
'blue'
'cyan'
'magenta'
'yellow'
'black'
'white'
'orange'
'purple'
'brown'
'pink'
'gray'
'lightgray'
'darkgray'

2. Hexadecimal Color Codes¶

You can use hex color codes (e.g., '#FF5733' for a shade of red). The format is #RRGGBB where RR, GG, and BB are hexadecimal values for red, green, and blue, respectively.¶

3. RGB and RGBA Tuples¶

Colors can also be specified using RGB or RGBA tuples:¶

RGB: A tuple of three floats representing red, green, and blue, each in the range [0, 1]. For example, (1, 0, 0) for red.¶

RGBA: A tuple of four floats, with the last one representing alpha (opacity). For example, (1, 0, 0, 0.5) for semi-transparent red.¶

4. Grayscale Values¶

You can specify a grayscale value as a string (e.g., '0.5' for medium gray) or as a float in the range [0, 1].¶

5. Colormaps¶

For continuous data, you can use colormaps. matplotlib provides a range of colormaps (e.g., viridis, plasma, cividis, etc.).¶

9. Adjust color in the plot¶

In [ ]:
plt.style.use('classic')
plt.rcParams.update({'font.size': 14})
fig = plt.figure(figsize=(3,2), facecolor='white')
plt.plot(x, y, 'o-', color= (1, 0, 0, 1), markersize=6)
# set color using (R,G,B,A) tuple where R is Red, G is Green, B is Blue, A is Alpha. All values range [0,1]

plt.xlim(0, 6)  # Set the range from 0 to 6
plt.ylim(0, 50)  # Set the range from 0 to 50
plt.title('Styled Line Plot')
plt.xlabel('Distance (m)') # using meaningful label will make it more clear
plt.ylabel('Height (m)')
plt.tick_params(width=2)  # Set tick width to 2
# Add grids
plt.grid(which='both', linestyle=':', linewidth=0.7, color='gray')  # You can customize these parameters

plt.show()

10. Checking Available Colormaps¶

In [ ]:
import matplotlib.cm as cm

from matplotlib import colormaps
df = pd.DataFrame(list(colormaps))
# Calculate the number of elements needed for reshaping
total_elements = 13 * 13  # 169 elements needed
current_elements = df.shape[0]  # Current number of elements (166)

# Pad the DataFrame with NaN values to reach 169 elements
padding_size = total_elements - current_elements  # Calculate padding size
if padding_size > 0:
    # Create a DataFrame with NaN values for padding
    padding = pd.DataFrame([np.nan] * padding_size, columns=['Value'])
    df_padded = pd.concat([df, padding], ignore_index=True)
else:
    df_padded = df

# Confirm the padded DataFrame's length
print(f"\nPadded DataFrame Length: {len(df_padded)}")

# Reshape the padded DataFrame to 13 by 13
reshaped_array = df_padded[0].values.reshape(13, 13)

# Convert the reshaped array back to a DataFrame
reshaped_df = pd.DataFrame(reshaped_array)

# Display the reshaped DataFrame
print("\nReshaped DataFrame (13 by 13):")
reshaped_df
Padded DataFrame Length: 169

Reshaped DataFrame (13 by 13):
Out[ ]:
0 1 2 3 4 5 6 7 8 9 10 11 12
0 magma inferno plasma viridis cividis twilight twilight_shifted turbo Blues BrBG BuGn BuPu CMRmap
1 GnBu Greens Greys OrRd Oranges PRGn PiYG PuBu PuBuGn PuOr PuRd Purples RdBu
2 RdGy RdPu RdYlBu RdYlGn Reds Spectral Wistia YlGn YlGnBu YlOrBr YlOrRd afmhot autumn
3 binary bone brg bwr cool coolwarm copper cubehelix flag gist_earth gist_gray gist_heat gist_ncar
4 gist_rainbow gist_stern gist_yarg gnuplot gnuplot2 gray hot hsv jet nipy_spectral ocean pink prism
5 rainbow seismic spring summer terrain winter Accent Dark2 Paired Pastel1 Pastel2 Set1 Set2
6 Set3 tab10 tab20 tab20b tab20c magma_r inferno_r plasma_r viridis_r cividis_r twilight_r twilight_shifted_r turbo_r
7 Blues_r BrBG_r BuGn_r BuPu_r CMRmap_r GnBu_r Greens_r Greys_r OrRd_r Oranges_r PRGn_r PiYG_r PuBu_r
8 PuBuGn_r PuOr_r PuRd_r Purples_r RdBu_r RdGy_r RdPu_r RdYlBu_r RdYlGn_r Reds_r Spectral_r Wistia_r YlGn_r
9 YlGnBu_r YlOrBr_r YlOrRd_r afmhot_r autumn_r binary_r bone_r brg_r bwr_r cool_r coolwarm_r copper_r cubehelix_r
10 flag_r gist_earth_r gist_gray_r gist_heat_r gist_ncar_r gist_rainbow_r gist_stern_r gist_yarg_r gnuplot_r gnuplot2_r gray_r hot_r hsv_r
11 jet_r nipy_spectral_r ocean_r pink_r prism_r rainbow_r seismic_r spring_r summer_r terrain_r winter_r Accent_r Dark2_r
12 Paired_r Pastel1_r Pastel2_r Set1_r Set2_r Set3_r tab10_r tab20_r tab20b_r tab20c_r NaN NaN NaN

11. Adding Anotation¶

In [ ]:
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
plt.style.use('classic')
plt.rcParams.update({'font.size': 14})
fig = plt.figure(figsize=(3,2), facecolor='white')
plt.plot(x, y, 'o-', color= (1, 0, 0, 1), markersize=6)
# set color using (R,G,B,A) tuple where R is Red, G is Green, B is Blue, A is Alpha. All values range [0,1]

plt.xlim(0, 6)  # Set the range from 0 to 6
plt.ylim(0, 50)  # Set the range from 0 to 50
plt.title('Styled Line Plot')
plt.xlabel('Distance (m)') # using meaningful label will make it more clear
plt.ylabel('Height (m)')
plt.tick_params(width=2)  # Set tick width to 2
# Add grids
plt.grid(which='both', linestyle=':', linewidth=0.7, color='gray')  # You can customize these parameters
plt.annotate('Highest Point', xy=(5, 40), xytext=(0.5, 35),
             arrowprops=dict(facecolor='black', arrowstyle='->'))
plt.show()

12. Save the figure before plt.show()¶

  • Use bbox_inches = 'tight' to in plt.savefig to resolve cutting edge of the png file
In [ ]:
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
plt.style.use('classic')
plt.rcParams.update({'font.size': 14})
fig = plt.figure(figsize=(5,3), facecolor='white')
plt.plot(x, y, 'o-', color= (1, 0, 0, 1), markersize=6)
# set color using (R,G,B,A) tuple where R is Red, G is Green, B is Blue, A is Alpha. All values range [0,1]

plt.xlim(0, 6)  # Set the range from 0 to 6
plt.ylim(0, 50)  # Set the range from 0 to 50
plt.title('Styled Line Plot')
plt.xlabel('Distance (m)') # using meaningful label will make it more clear
plt.ylabel('PM2.5 (\u03bcg/m\u00b3)')
plt.tick_params(width=2)  # Set tick width to 2
# Add grids
plt.grid(which='both', linestyle=':', linewidth=0.7, color='gray')  # You can customize these parameters
plt.annotate('Highest Point', xy=(5, 40), xytext=(0.5, 35),
             arrowprops=dict(facecolor='black', arrowstyle='->'))
plt.savefig('myplot.png', dpi=300, bbox_inches='tight')
# use bbox_inches = 'tight' to resolve cutting edge of the png file
plt.show()

Lowercase Greek Letters:¶

Symbol Name Unicode Escape¶

α   Alpha    \u03b1
β   Beta     \u03b2
γ   Gamma    \u03b3
δ   Delta    \u03b4
ε   Epsilon \u03b5
ζ   Zeta     \u03b6
η   Eta   \u03b7
θ   Theta    \u03b8
ι   Iota     \u03b9
κ   Kappa    \u03ba
λ   Lambda  \u03bb
μ   Mu    \u03bc
ν   Nu    \u03bd
ξ   Xi    \u03be
ο   Omicron \u03bf
π   Pi    \u03c0
ρ   Rho   \u03c1
σ   Sigma    \u03c3
τ   Tau   \u03c4
υ   Upsilon \u03c5
φ   Phi   \u03c6
χ   Chi   \u03c7
ψ   Psi   \u03c8
ω   Omega    \u03c9

Uppercase Greek Letters:¶

Symbol Name Unicode Escape¶

Α   Alpha   \u0391
Β   Beta    \u0392
Γ   Gamma   \u0393
Δ   Delta   \u0394
Ε   Epsilon \u0395
Ζ   Zeta    \u0396
Η   Eta \u0397
Θ   Theta   \u0398
Ι   Iota    \u0399
Κ   Kappa   \u039a
Λ   Lambda  \u039b
Μ   Mu  \u039c
Ν   Nu  \u039d
Ξ   Xi  \u039e
Ο   Omicron \u039f
Π   Pi  \u03a0
Ρ   Rho \u03a1
Σ   Sigma   \u03a3
Τ   Tau \u03a4
Υ   Upsilon \u03a5
Φ   Phi \u03a6
Χ   Chi \u03a7
Ψ   Psi \u03a8
Ω   Omega   \u03a9

Superscripts:¶

These are characters that appear slightly above the normal line of text. They are typically used for exponents or mathematical notations.¶

Symbol Description Unicode Escape¶

⁰   Superscript 0   \u2070
¹   Superscript 1   \u00b9
²   Superscript 2   \u00b2
³   Superscript 3   \u00b3
⁴   Superscript 4   \u2074
⁵   Superscript 5   \u2075
⁶   Superscript 6   \u2076
⁷   Superscript 7   \u2077
⁸   Superscript 8   \u2078
⁹   Superscript 9   \u2079
⁺   Superscript Plus    \u207a
⁻   Superscript Minus   \u207b
⁼   Superscript Equals  \u207c
⁽   Superscript Left Parenthesis    \u207d
⁾   Superscript Right Parenthesis   \u207e

Subscripts:¶

These are characters that appear slightly below the normal line of text. They are commonly used in chemical formulas or mathematical indices.¶

Symbol Description Unicode Escape¶

₀   Subscript 0 \u2080
₁   Subscript 1 \u2081
₂   Subscript 2 \u2082
₃    Subscript 3    \u2083
₄   Subscript 4 \u2084
₅   Subscript 5 \u2085
₆   Subscript 6 \u2086
₇   Subscript 7 \u2087
₈   Subscript 8 \u2088
₉   Subscript 9 \u2089
₊   Subscript Plus  \u208a
₋   Subscript Minus \u208b
₌   Subscript Equals    \u208c
₍   Subscript Left Parenthesis  \u208d
₎   Subscript Right Parenthesis \u208e

Creating subplots in Matplotlib is a powerful way to display multiple plots in a single figure¶

13. Basic Subplots¶

You can create a simple grid of subplots using plt.subplots(). Here's an example with a 2x2 grid:¶

In [ ]:
import matplotlib.pyplot as plt
import numpy as np

# Create data
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.exp(x / 10)

# Create a 2x2 grid of subplots
fig, axs = plt.subplots(2, 2, figsize=(8,6),facecolor='white')

# Set the style
plt.style.use('classic')
plt.rcParams.update({'font.size': 14})
# Plot data on each subplot
axs[0, 0].plot(x, y1, color='blue',linewidth=2)
axs[0, 0].set_title('Sine Wave')
axs[0, 0].set_xlabel('X-axis')
axs[0, 0].set_ylabel('Y-axis')

axs[0, 1].plot(x, y2, color='orange',linewidth=2)
axs[0, 1].set_title('Cosine Wave')
axs[0, 1].set_xlabel('X-axis')
axs[0, 1].set_ylabel('Y-axis')

axs[1, 0].plot(x, y3, color='green',linewidth=2)
axs[1, 0].set_title('Tangent Wave')
axs[1, 0].set_xlabel('X-axis')
axs[1, 0].set_ylabel('Y-axis')

axs[1, 1].plot(x, y4, color='red',linewidth=2)
axs[1, 1].set_title('Exponential Function')
axs[1, 1].set_xlabel('X-axis')
axs[1, 1].set_ylabel('Y-axis')

# Adjust layout
plt.tight_layout()
plt.show()

14. Sharing Axes¶

In [ ]:
# Create a 1x2 grid of subplots with shared y-axis
fig, axs = plt.subplots(1, 2, sharey=True, figsize=(8,4), facecolor='white')

# Plot data
axs[0].plot(x, y1, color='blue',linewidth=2)
axs[0].set_title('Sine Wave')
axs[0].set_xlabel('X-axis')

axs[1].plot(x, y2, color='orange',linewidth=2)
axs[1].set_title('Cosine Wave')
axs[1].set_xlabel('X-axis')

# Set shared y-label
axs[0].set_ylabel('Y-axis')

# Adjust layout
plt.tight_layout()
plt.show()

15. Different Plot Types¶

You can also mix different types of plots in subplots¶

In [ ]:
# Create a 2x2 grid of subplots with different plot types
fig, axs = plt.subplots(2, 2, figsize=(10, 8),facecolor='white')

# Line plot
axs[0, 0].plot(x, y1, color='blue',linewidth=2)
axs[0, 0].set_title('Sine Wave')

# Scatter plot
axs[0, 1].scatter(x, y2, color='orange')
axs[0, 1].set_title('Cosine Wave Scatter')

# Bar plot
axs[1, 0].bar(['A', 'B', 'C'], [1, 2, 3], color='pink')
axs[1, 0].set_title('Bar Plot')

# Histogram
axs[1, 1].hist(np.random.randn(1000), bins=30, color='gray')
axs[1, 1].set_title('Histogram')

# Adjust layout
plt.tight_layout()
plt.show()

16. Another way to create multiple plots in one figure¶

Using GridSpec¶

In [ ]:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)  # Sine wave
y2 = np.cos(x)  # Cosine wave
y3 = np.tan(x)  # Tangent wave
y4 = np.exp(x / 10)  # Exponential function

# Create a GridSpec with 3 rows and 2 columns
gs = GridSpec(3, 2)

# Create subplots using GridSpec
fig = plt.figure(figsize=(8,6),facecolor='white')

# Top left: Sine Wave
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(x, y1, color='blue', linewidth=2)
ax1.set_title('Sine Wave')

# Top right: Cosine Wave
ax2 = fig.add_subplot(gs[0, 1])
ax2.plot(x, y2, color='orange', linewidth=2)
ax2.set_title('Cosine Wave')

# Middle left: Tangent Wave
ax3 = fig.add_subplot(gs[1, 0])
ax3.plot(x, y3, color='green', linewidth=2)
ax3.set_title('Tangent Wave')

# Middle right: Exponential Function
ax4 = fig.add_subplot(gs[1, 1])
ax4.plot(x, y4, color='red', linewidth=2)
ax4.set_title('Exponential Function')

# Bottom: Combine two plots (full width)
ax5 = fig.add_subplot(gs[2, :])  # This subplot spans all columns
ax5.hist(np.random.randn(1000), bins=30, color='gray')
ax5.set_title('Histogram')

# Adjust layout
plt.tight_layout()
plt.show()
In [ ]: