Increment matplotlib color cycle

女生的网名这么多〃 提交于 2019-12-09 15:55:34

问题


Is there a simple way to increment the matplotlib color cycle without digging into axes internals?

When plotting interactively a common pattern I use is:

import matplotlib.pyplot as plt

plt.figure()
plt.plot(x,y1)
plt.twinx()
plt.plot(x,y2)

The plt.twinx() in necessary to get different y-scales for y1 and y2 but both plots are drawn with the first color in the default colorcycle making it necessary to manually declare the color for each plot.

There must be a shorthand way to instruct the second plot to increment the color cycle rather than explicitly giving the color. It is easy of course to set color='b' or color='r' for the two plots but when using a custom style like ggplot you would need need to lookup the color codes from the current colorcycle which is cumbersome for interactive use.


回答1:


You could call

ax2._get_lines.get_next_color()

to advance the color cycler on color. Unfortunately, this accesses the private attribute ._get_lines, so this is not part of the official public API and not guaranteed to work in future versions of matplotlib.

A safer but less direct way of advance the color cycler would be to plot a null plot:

ax2.plot([], [])

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y1 = np.random.randint(10, size=10)
y2 = np.random.randint(10, size=10)*100
fig, ax = plt.subplots()
ax.plot(x, y1, label='first')
ax2 = ax.twinx()
ax2._get_lines.get_next_color()
# ax2.plot([], [])
ax2.plot(x,y2, label='second')

handles1, labels1 = ax.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
ax.legend(handles1+handles2, labels1+labels2, loc='best')  

plt.show()




回答2:


You can cycle through the colour scheme as follows:

# Import Python cycling library
from itertools import cycle

# Create a colour code cycler e.g. 'C0', 'C1', etc.
colour_codes = map('C{}'.format, cycle(range(10)))

# Get next colour code
colour_code = next(colour_codes)



回答3:


Similar to the other answers but using matplotlib color cycler:

import matplotlib.pyplot as plt
from itertools import cycle

prop_cycle = plt.rcParams['axes.prop_cycle']
colors = cycle(prop_cycle.by_key()['color'])
for data in my_data:
    ax.plot(data.x, data.y, color=next(colors))


来源:https://stackoverflow.com/questions/37890412/increment-matplotlib-color-cycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!