4

I have a color scheme that comes from

plt.style.use('ggplot')

so I don't want to manually pick colors, or pick them from a color cycler. However, when I have a secondary axis:

fig, ax = plt.subplots()
ax2 = ax.twinx()
ax.plot(np.array([1, 2]))
ax2.plot(np.array([3, 4]))

It will plot both lines in the same color. How do I tell ax2 that there is already n=1 lines drawn on that plot, such that it starts with the n+1th color?

FooBar
  • 15,724
  • 19
  • 82
  • 171

3 Answers3

9

I think manually calling next() on the prop_cycler as suggested in the other answer is a bit error prone because it's easy to forget. In order to automate the process, you can make both axes share the same cycler:

ax2._get_lines.prop_cycler = ax1._get_lines.prop_cycler

Yes, it is still an ugly hack because it depends on the internal implementation details instead of a defined interface. But in the absence of an official feature, this is probably the most robust solution. As you can see, you can add plots on the two axes in any order, without manual intervention.

Complete code:

import matplotlib.pyplot as plt
import numpy as np

plt.style.use('ggplot')

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax2._get_lines.prop_cycler = ax1._get_lines.prop_cycler

ax1.plot(np.array([1, 2, 3]))
ax2.plot(np.array([3, 5, 4]))
ax1.plot(np.array([0, 1, 3]))
ax2.plot(np.array([2, 4, 1]))

plt.show()

Example plot

Fritz
  • 1,293
  • 15
  • 27
3

There is unfortunately no "recommended" way to manipulate the cycler state. See some in-depth discussion at Get matplotlib color cycle state.

You may however access the current cycler and advance it manually.

next(ax2._get_lines.prop_cycler)

Complete code:

import matplotlib.pyplot as plt
import numpy as np

plt.style.use('ggplot')

fig, ax = plt.subplots()
ax2 = ax.twinx()
ax.plot(np.array([1, 2, 3]))

next(ax2._get_lines.prop_cycler)
ax2.plot(np.array([3, 5,4]))

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
1

You can plot an empty list to ax2 before plotting your actual data. This causes the first colour in the cycle to be used to draw a line that doesn't really exist, moving on to the second colour for the real data.

plt.style.use("ggplot")
fig, ax = plt.subplots()
ax2 = ax.twinx()
ax.plot(np.array([1, 2]))

ax2.plot([])  # Plotting nothing.

ax2.plot(np.array([2, 1]))

Plotting nothing to skip a colour

mostlyoxygen
  • 981
  • 5
  • 14