Matplotlib color cycle increase

Is there an easy way to increase matplotlib color cycles without delving into internal axes?

When building an interactive image, I use the usual template:

import matplotlib.pyplot as plt

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

plt.twinx() you need to get different y-scales for y1 and y2, but both graphs are drawn with the first color in the default color cycle, which makes it necessary to manually declare a color for each graph.

There should be an abbreviated way of instructing a second plot to increase the color cycle rather than explicitly specifying a color. Of course, for two graphs it’s easy to set color='b'either color='r', but when using a custom style, such as ggplot, you will need to look for color codes for the current color cycle, which is cumbersome to use interactively.

+7
source share
3 answers

Could you call

ax2._get_lines.get_next_color()

to advance the color cycle by color. Unfortunately, this refers to a private attribute ._get_lines, so it is not part of the official public API and is not guaranteed to work in future versions of matplotlib.

A safer, but less direct way to develop the color cycle is to build a zero graph:

ax2.plot([], [])

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y1 = np.random.randint(10, size=10)
y2 = np.random.randint(10, size=10)*100
fig, ax = plt.subplots()
ax.plot(x, y1, label='first')
ax2 = ax.twinx()
ax2._get_lines.get_next_color()
# ax2.plot([], [])
ax2.plot(x,y2, label='second')

handles1, labels1 = ax.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
ax.legend(handles1+handles2, labels1+labels2, loc='best')  

plt.show()

enter image description here

+10
source

You can switch between color schemes as follows:

# Import Python cycling library
from itertools import cycle

# Create a colour code cycler e.g. 'C0', 'C1', etc.
colour_codes = map('C{}'.format, cycle(range(10)))

# Get next colour code
colour_code = next(colour_codes)
+3
source

Similar to other answers, but using color cyclic matplotlib:

import matplotlib.pyplot as plt
from itertools import cycle

prop_cycle = plt.rcParams['axes.prop_cycle']
colors = cycle(prop_cycle.by_key()['color'])
for data in my_data:
    ax.plot(data.x, data.y, color=next(colors))
0
source

All Articles