递增matplotlib颜色周期 [英] Increment matplotlib color cycle

查看:88
本文介绍了递增matplotlib颜色周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来增加matplotlib颜色循环而无需深入轴内部?

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)

为了获得y1和y2不同的y比例,必须使用plt.twinx(),但是两个图均使用默认颜色周期中的第一种颜色绘制,因此必须手动声明每个图的颜色.

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.

必须有一种简便的方法来指示第二个绘图增加颜色循环,而不是显式给出颜色.当然,为两个图设置color='b'color='r'很容易,但是当使用自定义样式(例如ggplot)时,您需要从当前色环中查找颜色代码,这对于交互使用来说很麻烦.

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.

推荐答案

您可以致电

ax2._get_lines.get_next_color()

使颜色循环器上的颜色前进.不幸的是,它访问私有属性._get_lines,因此它不是官方公共API的一部分,并且不能保证在matplotlib的未来版本中可以使用.

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()

这篇关于递增matplotlib颜色周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆