Joh*_*xon 14 python plot matplotlib
在matplotlib中,我想创建一个使用matplotlib.pyplot
黑色和黄色交替的线条,然后我想在图例上包含该线条.我怎么做?
我可以这样做:
from matplotlib import pyplot as plt, gridspec
import numpy as np
grid = gridspec.GridSpec(1,1)
ax = plt.subplot(grid[0,0])
x = np.arange(1,11)
y = x * 2
ax.plot(x, y, '-', color = 'black', linewidth = 1, label = 'my line')
ax.plot(x, y, '--', color = 'yellow')
ax.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)
但是传说中的线条将显示为黑色实线,而不是黑色和黄色的虚线.
我确实看过,matplotlib.path_effects
但我无法弄清楚是否有可能达到我的目的; 我可以勾勒出阴影线或阴影线,但我不确定我是否可以覆盖不同颜色的虚线.
Tan*_*her 13
试试这个.
from matplotlib import pyplot as plt, gridspec, lines
import numpy as np
grid = gridspec.GridSpec(1,1)
ax = plt.subplot(grid[0,0])
x = np.arange(1,11)
y = x * 2
ax.plot(x, y, '-', color = 'black', linewidth = 5)
ax.plot(x, y, '--', color = 'lawngreen', linewidth = 5)
dotted_line1 = lines.Line2D([], [], linewidth=5, linestyle="--", dashes=(10, 1), color='lawngreen')
dotted_line2 = lines.Line2D([], [], linewidth=5, linestyle="-", dashes=(5, 4), color='black')
plt.legend([(dotted_line1, dotted_line2)], ["My Line"])
plt.show()
Run Code Online (Sandbox Code Playgroud)
我增加了线宽,使其清晰可见.因为黄色在白色背景下不那么清晰; 将其改为绿色.对于那个很抱歉.你可以随时改变颜色:)