How can I get the color of the last figure in Matplotlib?

In Matplotlib, you can retrieve the color of any plotted line using the get_color() method. This is particularly useful when you want to identify the automatically assigned colors or when working with multiple plots in the same figure.

Basic Example

Let's start with a simple example to understand how get_color() works ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create data points
x = np.arange(10)

# Plot multiple lines
p = plt.plot(x, x, x, x ** 2, x, x ** 3)

# Add legend
plt.legend([p[0], p[1], p[2]], ["$y=x$", "$y=x^2$", "$y=x^3$"])

# Get colors of each plot
print("Color of the first plot:", p[0].get_color())
print("Color of the second plot:", p[1].get_color())
print("Color of the third plot:", p[2].get_color())

plt.show()

The output of the above code is ?

Color of the first plot: #1f77b4
Color of the second plot: #ff7f0e
Color of the third plot: #2ca02c

Getting the Last Plot Color Specifically

To get only the color of the last figure/plot, access the last element from the plot list ?

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(5)

# Multiple plots
plots = plt.plot(x, x, x, x**2, x, x**3)

# Get the color of the last plot only
last_plot_color = plots[-1].get_color()
print("Color of the last plot:", last_plot_color)

plt.show()

The output of the above code is ?

Color of the last plot: #2ca02c

Alternative Method Using gca()

You can also retrieve the last plot's color using the current axes ?

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(5)

plt.plot(x, x, label='Linear')
plt.plot(x, x**2, label='Quadratic') 
plt.plot(x, x**3, label='Cubic')

# Get the last line from current axes
ax = plt.gca()
last_line = ax.get_lines()[-1]
last_color = last_line.get_color()

print("Last plot color:", last_color)
plt.legend()
plt.show()

The output of the above code is ?

Last plot color: #2ca02c

Key Points

  • plot() returns a list of Line2D objects when plotting multiple lines
  • Use [-1] index to access the last plot from the returned list
  • get_color() returns the color as a hex string (e.g., '#1f77b4')
  • gca().get_lines()[-1] provides an alternative way to access the last line

Conclusion

Use get_color() method on the last element of the plot list to retrieve the color of the last figure. This method works with both single and multiple plot scenarios in Matplotlib.

Updated on: 2026-03-25T22:58:23+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements