在下面我试图绘制颜色和标签的点,每个j都会改变。我得到的是每个情侣(i,j)的不同颜色和图例中的一个标签:
import itertools
import numpy as np
import matplotlib.pyplot as plt
color_list = ["blue", "brown", "red", "black"]
g = itertools.cycle(color_list)
primes = (139,149,151,157,163,167)
for j in range(50, 300, 10):
col = next(g)
for k in (primes):
for l in range(10000, 20000, 500):
start = time.time()
generator(j, k, l)
end = time.time()
plt.plot(l, end - start, linewidth = 2, marker='o', color=col)
编辑:使用我原来的问题更新了代码,因为我无法弄清楚Ernest + Arya的解决方案是否适用于这种情况。
答案 0 :(得分:1)
您可以使用matplotlib cycler。设置要迭代的颜色列表,然后在j
- 循环内,获取my_cycle.next()
的颜色。然后将该颜色传递到您对plt.plot
的调用中。
答案 1 :(得分:1)
i
上的第二个循环不是没用吗?
import numpy as np
import matplotlib.pyplot as plt
for j in range (0, 2):
x = np.arange(0,9,2)
y = np.ones_like(x)*j + 0.5
plt.plot(x,y, marker='o', label='$n = {j}$'.format(j=j))
plt.legend()
plt.show()
更新问题的解决方案:
import itertools
import numpy as np
import matplotlib.pyplot as plt
color_list = ["blue", "brown", "red", "black"]
g = itertools.cycle(color_list)
for j in range (0, 2):
col = next(g)
x = np.arange(0,9,2)
y = np.ones_like(x)*j + 0.5
plt.plot(x,y, marker='o', color=col, label='$n = {j}$'.format(j=j))
plt.legend()
plt.show()
第二次更新的解决方案;这个想法总是一样的:使用尽可能多的plt.plot()
来电,因为你想拥有不同的颜色/图例条目。
import numpy as np
import matplotlib.pyplot as plt
import time
def generator(j,k,l):
#some operation that takes a little time
a = np.random.rand(k % 7, l-1000, j%13 )
return a
color_list = ["blue", "brown", "red", "black"]
primes = (139,149,151,157,163,167)
for j in range(50, 300, 25):
x = []; y = []
for k in (primes):
for l in range(10000, 20000, 1000):
start = time.time()
generator(j, k, l)
end = time.time()
x.append(l); y.append(end - start)
plt.plot(x,y, ls="", marker='o', label='$n = {j}$'.format(j=j))
plt.legend()
plt.show()
答案 2 :(得分:1)
您可以使用sin或cos函数来控制颜色选择,并添加一个仅在j更改时更改的变量,以控制是否绘制新标签
import numpy as np
import matplotlib.pyplot as plt
import math
last_j = -1
z = 5
for j in range (0, z):
color = ((math.sin(j)+1)/2,(math.cos(j+1)+1)/2,(math.cos(j)+1)/2)
for i in range (0, 10, 2):
if j == last_j:
plt.plot(i + 0.5, j + 0.5, c=color, linewidth = 2, marker='o')
else:
plt.plot(i + 0.5, j + 0.5, c=color, linewidth = 2, marker='o',
label='$n = {j}$'.format(j=j))
last_j = j
ax = plt.gca()
legend = ax.legend(loc = 'center right', shadow=True)
plt.show()