Twinx/Secondary-y:不要从第一种颜色开始 [英] Twinx/Secondary-y: Do not start with first color
问题描述
我有一个来自
的配色方案plt.style.use('ggplot')
所以我不想手动选择颜色,或者从颜色循环器中选择它们.但是,当我有辅助轴时:
fig, ax = plt.subplots()ax2 = ax.twinx()ax.plot(np.array([1, 2]))ax2.plot(np.array([3, 4]))
它将以相同的颜色绘制两条线.我该如何告诉 ax2
该图上已经绘制了 n = 1
条线,使得它以第 n + 1
个颜色开始?
我认为在 prop_cycler
上手动调用 next()
如
I have a color scheme that comes from
plt.style.use('ggplot')
so I don't want to manually pick colors, or pick them from a color cycler. However, when I have a secondary axis:
fig, ax = plt.subplots()
ax2 = ax.twinx()
ax.plot(np.array([1, 2]))
ax2.plot(np.array([3, 4]))
It will plot both lines in the same color. How do I tell ax2
that there is already n=1
lines drawn on that plot, such that it starts with the n+1
th color?
I think manually calling next()
on the prop_cycler
as suggested in the other answer is a bit error prone because it's easy to forget. In order to automate the process, you can make both axes share the same cycler:
ax2._get_lines.prop_cycler = ax1._get_lines.prop_cycler
Yes, it is still an ugly hack because it depends on the internal implementation details instead of a defined interface. But in the absence of an official feature, this is probably the most robust solution. As you can see, you can add plots on the two axes in any order, without manual intervention.
Complete code:
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax2._get_lines.prop_cycler = ax1._get_lines.prop_cycler
ax1.plot(np.array([1, 2, 3]))
ax2.plot(np.array([3, 5, 4]))
ax1.plot(np.array([0, 1, 3]))
ax2.plot(np.array([2, 4, 1]))
plt.show()
这篇关于Twinx/Secondary-y:不要从第一种颜色开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!