Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twinx/Secondary-y: Do not start with first color

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?

like image 913
FooBar Avatar asked Dec 17 '22 22:12

FooBar


1 Answers

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

like image 132
Fritz Avatar answered Jan 05 '23 00:01

Fritz