How to plot multiple lines in matplotlib with different colors?

Matplotlib is a popular Python library used for data visualization and plotting. It provides a wide range of customizable plots and charts that can be used in Python scripts, Jupyter notebooks, and Tkinter GUIs.

A common task when using matplotlib is to plot multiple lines on the same graph, with each line having a distinct color. This allows you to visualize and compare multiple datasets on a single plot. In this post, we will cover several methods to plot multiple lines with different colors using matplotlib.

Prerequisites

Before we dive into the code, let’s go over some prerequisites:

• Python 3.x installed
• Matplotlib library installed (e.g. `pip install matplotlib`)
• Basic knowledge of Python and matplotlib
• Sample data to plot (we’ll use some dummy data in this post)

Method 1: Specifying Colors in plt.plot()

The simplest way to use different colors when plotting multiple lines is to specify the `color` keyword argument in each `plt.plot()` call:

``````import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, color='r')
plt.plot(x, y2, color='g')

plt.title('Sine and Cosine')
plt.xlabel('x values')
plt.ylabel('y values')
plt.legend(['Sine', 'Cosine'])
plt.show()
``````

Here we specify `'r'` for red and `'g'` for green. This will plot the sine function in red and cosine in green.

We can use any matplotlib supported color abbreviations like:

• ‘b’ – blue
• ‘g’ – green
• ‘r’ – red
• ‘c’ – cyan
• ‘m’ – magenta
• ‘y’ – yellow
• ‘k’ – black
• ‘w’ – white

Or we can use hex color codes like `'#FF00FF'` for purple.

Method 2: Creating a colormap

Another method is to define a colormap that maps data values to colors. This allows coloring lines based on a numeric array.

For example:

``````import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

colormap = np.array(['r', 'g'])

plt.plot(x, y1, color=colormap[0])
plt.plot(x, y2, color=colormap[1])

plt.title('Sine and Cosine')
# Rest is same
``````

Here we create a colormap array with ‘r’ and ‘g’, then use indexing to color the sine and cosine plots.

This method is useful when you have many lines to plot and want to keep the color mapping organized.

Method 3: Using a colormap object

Matplotlib has built-in colormap objects that can map data values to colors. For instance:

``````import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, color=cm.Reds(0.5))
plt.plot(x, y2, color=cm.Greens(0.5))

# Rest is same
``````

Here we imported the `cm` module and used the `Reds` and `Greens` colormap objects. By passing a value between 0-1 we get an interpolated color from those colormaps.

Some other useful built-in colormaps are:

• cm.Blues
• cm.Greens
• cm.Oranges
• cm.Purples
• cm.Greys

This provides an easy way to select a color palette for your plots.

Method 4: Creating custom colormaps

You can also create custom colormaps by defining a list of RGB values:

``````import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap

x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

colors = [(1, 0, 0), (0, 1, 0)]
cmap = LinearSegmentedColormap.from_list('custom', colors, N=2)

plt.plot(x, y1, color=cmap(0))
plt.plot(x, y2, color=cmap(1))

# Rest is same
``````

Here we define a list of RGB tuples, then create a LinearSegmentedColormap from that list. We can index into the colormap to get colors. This lets you fully customize a color palette for your data.

Method 5: Using matplotlib styles

Matplotlib has several built-in plotting styles that come with color palettes. We can use these to easily color lines:

``````import matplotlib.pyplot as plt
import numpy as np

plt.style.use('fivethirtyeight')

x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1)
plt.plot(x, y2)

# Rest is same
``````

Here we used the `'fivethirtyeight'` style, which applies a color palette to the plots. Some other useful styles are:

• ‘ggplot’
• ‘seaborn’
• ‘Solarize_Light2’
• ‘bmh’

Styles provide pre-made color palettes, font customizations, and other theme elements.

Method 6: Iterating through a colormap

We can write a loop to automatically iterate through a colormap when plotting many lines:

``````import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

x = np.arange(0, 10, 0.1)
y_data = np.random.randn(5, len(x)) # 5 random lines

cmap = cm.get_cmap('rainbow', 5)  # 5 colors from rainbow colormap

for i in range(5):
y = y_data[i]
color = cmap(i)
plt.plot(x, y, color=color)

plt.title('5 Random Lines')
# Rest is same
``````

Here we generated 5 random datasets, then looped through and plotted each one using a different color from the rainbow colormap. This provides an easy way to plot many lines from a colormap.

Method 7: Using pandas and seaborn

If your data is in a Pandas dataframe, you can use seaborn to conveniently plot multiple columns as different colored lines:

``````import pandas as pd
import seaborn as sns

df = pd.DataFrame(np.random.randn(30, 5), columns=['a', 'b', 'c', 'd', 'e'])

sns.lineplot(data=df)

plt.title('Random Dataframe')
plt.xlabel('Index')
plt.ylabel('Values')
``````

Seaborn will automatically color each column differently. It uses smart default colors, but we can customize the palette as well.

Controlling other line properties

In addition to color, we may want to adjust other line properties like style, width, transparency, etc. Some examples:

``````# Line style
plt.plot(x, y, linestyle='dashed')

# Line width
plt.plot(x, y, linewidth=3)

# Alpha/transparency
plt.plot(x, y, alpha=0.5)

# Markers
plt.plot(x, y, marker='o')

# Marker size
plt.plot(x, y, markersize=10)

# Marker color
plt.plot(x, y, markeredgecolor='g')
``````

We can use these line properties in combination with colors to fully customize the plot output.

Controlling the legend

When plotting multiple lines, we often want to show a legend to identify what each line represents. There are a few ways to do this:

``````# 1. Automatically create legend from labels
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
plt.legend()

# 2. Manually create legend
plt.plot(x, y1)
plt.plot(x, y2)
plt.legend(['Line 1', 'Line 2'])

# 3. No legend
plt.plot(x, y1)
plt.plot(x, y2)
plt.legend([], []) # empty lists
``````

The legend can be customized further with properties like location, font size, color, etc.

Saving the plot to file

After creating the desired multi-line plot, we can save it to an image file using plt.savefig():

``````# Save figure
plt.savefig('plot.png')

# Specify dpi
plt.savefig('plot.png', dpi=300)

# Save just the portion inside axes
plt.savefig('plot.png', bbox_inches='tight')
``````

Some common file formats are .png, .jpg, .svg, .pdf. The dpi parameter controls resolution.

Plotting methodology summary

Here is a quick summary of the overall process for plotting multiple lines with different colors in matplotlib:

1. Import matplotlib and numpy
2. Prepare the x and y data to plot
3. Choose a color palette (single colors, colormap, etc)
4. Plot each line with plt.plot(), specifying the color
5. Customize line properties like width, style, transparency
6. Add a legend to identify the lines
7. Customize the plot labels, limits, etc
8. Save the figure to file (optional)
9. Show the plot

Conclusion

In this post we looked at various methods for plotting multiple lines with different colors in matplotlib. Some key takeaways:

• Use color and label arguments in plt.plot() for simple cases
• Create colormaps for more organized coloring from data
• Leverage built-in colormaps like cm.Blues and styles like ‘ggplot’
• Iterate through colormaps when plotting many lines
• Use seaborn for quick visualization from dataframes
• Customize line properties like width, transparency, markers
• Add legends to identify each line

Matplotlib provides a flexible API for diverse plotting needs. The key is go beyond basic single-line plots and leverage colormaps, iterators, styles to build informative multi-line visualizations.