1

I'm trying to plot a distribution and it's mean:

import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')

numbers = np.random.rand(100)
fig, ax = plt.subplots()
ax.hist(numbers)
ax.axvline(numbers.mean())

which will plot a red line on top of a red distribution. Importantly, I want to use the colors from my color scheme (gglot), and hence I do not want to manually select colors, or even a color cycle.

Recently, I learned that if I want to "force" the color cycler to use the next color, I can do

next(ax._get_lines.prop_cycler)

However, adding that line in between the hist and axvline does not help here. How could I "force" hist and axvline to follow the colors from my style?

FooBar
  • 15,724
  • 19
  • 82
  • 171

1 Answers1

4

You need to get the next color in the cycle by using

next(ax._get_lines.prop_cycler)['color']

You then need to explicitly use this in the color= argument of axvline:

plt.style.use('ggplot')

numbers = np.random.rand(100)
fig, ax = plt.subplots()
ax.hist(numbers)

ax.axvline(numbers.mean(), color = next(ax._get_lines.prop_cycler)['color'])

plt.show()

Which gives:

enter image description here

DavidG
  • 24,279
  • 14
  • 89
  • 82