Patrick
Patrick

Reputation: 1929

Why is the axis color cycle reduced to a single color when setting some other property cycle?

In python/matplotlib:

When I set the "marker" property cycle (for example), the color cycle just yields a constant (blue) color. See example below.

from matplotlib import pyplot as plt
import numpy as np

fig, (ax1,ax2) = plt.subplots(nrows=2)

ax1.set_prop_cycle(marker=['o','s','x','+','*'])

xx = np.arange(10)
for n in xx:
  ax1.plot(xx, n*xx)
  ax2.plot(xx, n*xx)

plt.show()

Result: screenshot

How can I get the color cycle to remain what it was, as in the 2nd axis?

Upvotes: 1

Views: 202

Answers (2)

Sheldore
Sheldore

Reputation: 39052

You can extract the color_cycle using rcParams and assign them as the colors for ax1 as (matplotlib version 2.0.2)

 ax1.set_prop_cycle(marker=['o','s','x','+','*'], color=plt.rcParams['axes.color_cycle'])

The colors might be different on your machine but will be consistent in both the plots.

EDIT (@ImportanceOfBeingEarnest's suggestion in the comments) in case of depreciation warning

ax1.set_prop_cycle(marker=['o','s','x','+','*'], color=plt.rcParams["axes.prop_cycle"].by_key()["color"][:5])

Output

enter image description here

Upvotes: 2

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339200

The property cycler can comprise of different properties, such as color, maker, linestyle etc. When setting the property cycler via ax1.set_prop_cycle(marker=[...]) you create a new property cycler which only contains a marker property, but no color.

In order to have a marker and color property you either need to set both, or extent the current property cycler by the property you want to change. The latter would be shown in the following.

from matplotlib import pyplot as plt
import numpy as np

fig, (ax1,ax2) = plt.subplots(nrows=2)

cycler = plt.rcParams["axes.prop_cycle"]
cycler += plt.cycler(marker=['o','s','x','+','*'])
ax1.set_prop_cycle(cycler)


colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
cycler2 = plt.cycler(color=colors)
cycler2 *= plt.cycler(marker=['o','s','x','+','*'])
ax2.set_prop_cycle(cycler2)

xx = np.arange(10)
for n in xx:
  ax1.plot(xx, n*xx)
  ax2.plot(xx, n*xx)

plt.show()

enter image description here

Note the difference between addition and multiplication here.

Upvotes: 3

Related Questions