Twinx/secondary-y: Do Not Start With First Color
Solution 1:
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()
Solution 2:
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()
Solution 3:
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]))
Post a Comment for "Twinx/secondary-y: Do Not Start With First Color"