Mik*_*ike 8 python matplotlib jupyter-notebook
有没有一种简单的方法来增加matplotlib颜色循环而不需要挖掘轴内部?
交互式绘制我使用的常见模式时:
import matplotlib.pyplot as plt
plt.figure()
plt.plot(x,y1)
plt.twinx()
plt.plot(x,y2)
Run Code Online (Sandbox Code Playgroud)
将plt.twinx()在必要时得到不同的Y尺度为Y1和Y2,但两条曲线均在默认colorcycle第一颜色使它必须手动声明为每个情节的颜色绘制.
必须有一种速记方式来指示第二个绘图增加颜色循环而不是明确地给出颜色.当然很容易设置color='b'或color='r'用于两个图,但是当使用自定义样式时,ggplot您需要从当前颜色循环中查找颜色代码,这对于交互式使用来说是麻烦的.
unu*_*tbu 10
你可以打电话
ax2._get_lines.get_next_color()
Run Code Online (Sandbox Code Playgroud)
在彩色上推进彩色循环仪.不幸的是,这会访问私有属性._get_lines,因此这不是官方公共API的一部分,并且不能保证在未来版本的matplotlib中工作.
一种更安全但不太直接的推进色彩循环器的方法是绘制零图:
ax2.plot([], [])
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
Pyplot 中有多种可用的配色方案。您可以阅读 matplotlib 教程指定颜色的更多内容。
从这些文档中:
a "CN" color spec, i.e. 'C' followed by a number, which is an index into the
default property cycle (matplotlib.rcParams['axes.prop_cycle']); the indexing
is intended to occur at rendering time, and defaults to black if the cycle
does not include color.
Run Code Online (Sandbox Code Playgroud)
您可以按如下方式循环选择配色方案:
a "CN" color spec, i.e. 'C' followed by a number, which is an index into the
default property cycle (matplotlib.rcParams['axes.prop_cycle']); the indexing
is intended to occur at rendering time, and defaults to black if the cycle
does not include color.
Run Code Online (Sandbox Code Playgroud)
这可以通过直接循环来改进matplotlib.rcParams['axes.prop_cycle']。
与其他答案类似,但使用 matplotlib 颜色循环器:
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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3367 次 |
| 最近记录: |