我可以在 matplotlib 中循环使用线条样式吗

发布于 2024-12-10 13:26:06 字数 101 浏览 1 评论 0原文

我知道如何在 matplotlib 中循环显示颜色列表。但是是否可以对线条样式(纯线、点线、虚线等)做类似的事情?我需要这样做,以便我的图表在打印时更容易阅读。有什么建议如何做到这一点吗?

I know how to cycle through a list of colors in matplotlib. But is it possible to do something similar with line styles (plain, dotted, dashed, etc.)? I'd need to do that so my graphs would be easier to read when printed. Any suggestions how to do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

黯然#的苍凉 2024-12-17 13:26:06

像这样的事情可能会成功:

import matplotlib.pyplot as plt
from itertools import cycle
lines = ["-","--","-.",":"]
linecycler = cycle(lines)
plt.figure()
for i in range(10):
    x = range(i,i+10)
    plt.plot(range(10),x,next(linecycler))
plt.show()

结果:
在此处输入图像描述

编辑更新版本 (v2.22)

import matplotlib.pyplot as plt
from cycler import cycler
#
plt.figure()
for i in range(5):
    x = range(i,i+5)
    linestyle_cycler = cycler('linestyle',['-','--',':','-.'])
    plt.rc('axes', prop_cycle=linestyle_cycler)
    plt.plot(range(5),x)
    plt.legend(['first','second','third','fourth','fifth'], loc='upper left', fancybox=True, shadow=True)
plt.show()

有关更多详细信息,请参阅有关“使用 Cycler 进行样式设置”的 matplotlib 教程
要查看输出,请单击“显示图

Something like this might do the trick:

import matplotlib.pyplot as plt
from itertools import cycle
lines = ["-","--","-.",":"]
linecycler = cycle(lines)
plt.figure()
for i in range(10):
    x = range(i,i+10)
    plt.plot(range(10),x,next(linecycler))
plt.show()

Result:
enter image description here

Edit for newer version (v2.22)

import matplotlib.pyplot as plt
from cycler import cycler
#
plt.figure()
for i in range(5):
    x = range(i,i+5)
    linestyle_cycler = cycler('linestyle',['-','--',':','-.'])
    plt.rc('axes', prop_cycle=linestyle_cycler)
    plt.plot(range(5),x)
    plt.legend(['first','second','third','fourth','fifth'], loc='upper left', fancybox=True, shadow=True)
plt.show()

For more detailed information consult the matplotlib tutorial on "Styling with cycler"
To see the output click "show figure"

梦太阳 2024-12-17 13:26:06

即将推出的 matplotlib v1.5 将针对新的 prop_cycler 功能弃用 color_cycle:http://matplotlib.org/devdocs/users/whats_new.html?highlight=prop_cycle#added-axes-prop-cycle-key-to-rcparams

plt.rcParams['axes.prop_cycle'] = ("cycler('color', 'rgb') +"
                                   "cycler('lw', [1, 2, 3])")

然后继续创建您的轴和图!

The upcoming matplotlib v1.5 will deprecate color_cycle for the new prop_cycler feature: http://matplotlib.org/devdocs/users/whats_new.html?highlight=prop_cycle#added-axes-prop-cycle-key-to-rcparams

plt.rcParams['axes.prop_cycle'] = ("cycler('color', 'rgb') +"
                                   "cycler('lw', [1, 2, 3])")

Then go ahead and create your axes and plots!

左耳近心 2024-12-17 13:26:06

这里有一些使用循环器开发样式集的示例,

可以添加循环器以给出组合(红色带有“-”,蓝色带有“--”,...)

plt.rc('axes', prop_cycle=(cycler('color', list('rbgk')) +
                           cycler('linestyle', ['-', '--', ':', '-.'])))

直接在轴上使用:

ax1.set_prop_cycle(cycler('color', ['c', 'm', 'y', 'k']) +
                   cycler('lw', [1, 2, 3, 4]))

循环器可以相乘(http://matplotlib.org/cycler/) 提供更广泛的独特样式

for ax in axarr:
    ax.set_prop_cycle(cycler('color', list('rbgykcm')) *
                      cycler('linestyle', ['-', '--']))

另请参阅:http://matplotlib.org/examples/color/color_cycle_demo.html

here's a few examples of using the cyclers to develop sets of styles

cyclers can be added to give compositions (red with '-', blue with '--', ...)

plt.rc('axes', prop_cycle=(cycler('color', list('rbgk')) +
                           cycler('linestyle', ['-', '--', ':', '-.'])))

direct use on Axes:

ax1.set_prop_cycle(cycler('color', ['c', 'm', 'y', 'k']) +
                   cycler('lw', [1, 2, 3, 4]))

cyclers can be multiplied (http://matplotlib.org/cycler/) to give a wider range of unique styles

for ax in axarr:
    ax.set_prop_cycle(cycler('color', list('rbgykcm')) *
                      cycler('linestyle', ['-', '--']))

see also: http://matplotlib.org/examples/color/color_cycle_demo.html

我的痛♀有谁懂 2024-12-17 13:26:06

如果您希望更改自动进行,您可以将这两行添加到
matplotlib的axes.py文件:
查找该行:

   self.color_cycle = itertools.cycle(clist)

并在下面添加以下行:

   self.line_cycle = itertools.cycle(["-",":","--","-.",])

并查找该行:

   kw['color'] = self.color_cycle.next()

并添加该行:

   kw['linestyle'] = self.line_cycle.next()

我想您可以对标记执行相同的操作。

If you want the change to be automatic you can add this two lines in
the axes.py file of matplotlib:
Look for that line:

   self.color_cycle = itertools.cycle(clist)

and add the following line underneath:

   self.line_cycle = itertools.cycle(["-",":","--","-.",])

And look for the line:

   kw['color'] = self.color_cycle.next()

and add the line:

   kw['linestyle'] = self.line_cycle.next()

I guess you can do the same for marker.

无人问我粥可暖 2024-12-17 13:26:06

我通常使用基本颜色和线条样式的组合来表示不同的数据集。假设我们有 16 个数据集,每四个数据集属于某个组(具有某些共同属性),那么当我们用共同的颜色表示每个组但其成员用不同的线条样式表示时,很容易可视化。

import numpy as np
import matplotlib.pyplot as plt

models=['00','01', '02', '03', '04', '05', '06', '07', '08', '09', '10',\
    '11', '12', '13', '14', '15', '16']

fig = plt.figure()
ax  = fig.add_subplot(111)

x = np.linspace(-1,1,100)
y = np.sin(x)

clrs_list=['k','b','g','r'] # list of basic colors
styl_list=['-','--','-.',':'] # list of basic linestyles

for i in range(0,16):
    clrr=clrs_list[i // 4]
    styl=styl_list[i % 4]
    modl=models[i+1]
    frac=(i+1)/10.0
    ax.plot(x,y+frac,label=modl,color=clrr,ls=styl)

plt.legend()
plt.show()

输入图像描述这里

I usually use a combination of basic colors and linestyles to represent different data sets. Suppose we have 16 data sets, each four data sets belonging to some group (having some property in common), then it is easy to visualize when we represent each group with a common color but its members with different line styles.

import numpy as np
import matplotlib.pyplot as plt

models=['00','01', '02', '03', '04', '05', '06', '07', '08', '09', '10',\
    '11', '12', '13', '14', '15', '16']

fig = plt.figure()
ax  = fig.add_subplot(111)

x = np.linspace(-1,1,100)
y = np.sin(x)

clrs_list=['k','b','g','r'] # list of basic colors
styl_list=['-','--','-.',':'] # list of basic linestyles

for i in range(0,16):
    clrr=clrs_list[i // 4]
    styl=styl_list[i % 4]
    modl=models[i+1]
    frac=(i+1)/10.0
    ax.plot(x,y+frac,label=modl,color=clrr,ls=styl)

plt.legend()
plt.show()

enter image description here

醉梦枕江山 2024-12-17 13:26:06

我使用与此类似的代码来循环不同的线条样式。默认情况下,颜色在 7 个绘图后重复。

idx = 0
for ds in datasets:
    if idx < 7:
        plot(ds)
    elif idx < 14:
        plot(ds, linestyle='--')
    else:
        plot(ds, linestyle=':')
    idx += 1

I use code similar to this one to cycle through different linestyles. By default colours repeat after 7 plots.

idx = 0
for ds in datasets:
    if idx < 7:
        plot(ds)
    elif idx < 14:
        plot(ds, linestyle='--')
    else:
        plot(ds, linestyle=':')
    idx += 1
战皆罪 2024-12-17 13:26:06

与 Avaris 图相似但不同......

import matplotlib.pyplot as plt
import numpy as np

#set linestyles (for-loop method)
colors=('k','y','m','c','b','g','r','#aaaaaa')
linestyles=('-','--','-.',':')
styles=[(color,linestyle) for linestyle in linestyles for color in colors]

#-- sample data
numLines=30
dataXaxis=np.arange(0,10)
dataYaxis=dataXaxis+np.array([np.arange(numLines)]).T


plt.figure(1)

#-----------
# -- array oriented method but I cannot set the line color and styles
# -- without changing Matplotlib code
plt.plot(datax[:,np.newaxis],datay.T)
plt.title('Default linestyles - array oriented programming')
#-----------

#-----------
# -- 'for loop' based approach to enable colors and linestyles to be specified

plt.figure(2)

for num in range(datay.sh![enter image description here][1]ape[0]):
    plt.plot(datax,datay[num,:],color=styles[num][0],ls=styles[num][1])
plt.title('User defined linestyles using for-loop programming')
#-----------

plt.show()

Similar to Avaris graphs but different....

import matplotlib.pyplot as plt
import numpy as np

#set linestyles (for-loop method)
colors=('k','y','m','c','b','g','r','#aaaaaa')
linestyles=('-','--','-.',':')
styles=[(color,linestyle) for linestyle in linestyles for color in colors]

#-- sample data
numLines=30
dataXaxis=np.arange(0,10)
dataYaxis=dataXaxis+np.array([np.arange(numLines)]).T


plt.figure(1)

#-----------
# -- array oriented method but I cannot set the line color and styles
# -- without changing Matplotlib code
plt.plot(datax[:,np.newaxis],datay.T)
plt.title('Default linestyles - array oriented programming')
#-----------

#-----------
# -- 'for loop' based approach to enable colors and linestyles to be specified

plt.figure(2)

for num in range(datay.sh![enter image description here][1]ape[0]):
    plt.plot(datax,datay[num,:],color=styles[num][0],ls=styles[num][1])
plt.title('User defined linestyles using for-loop programming')
#-----------

plt.show()
GRAY°灰色天空 2024-12-17 13:26:06

我喜欢使用循环器的答案,但使用最新版本的 matplotlib (3.7)您可以简单地传递值列表并让 matplotlib 构建循环器。例如,这是有效的:

axis.set_prop_cycle(color = ['c', 'm', 'y', 'k'],
                    lw = [1, 2, 3, 4])

并且它更整洁(例如与此相比),您不需要导入循环仪。

I like the answers making use of cyclers, but with the latest version of matplotlib (3.7) you can simply pass lists of values and let matplotlib build the cyclers. For example, this works:

axis.set_prop_cycle(color = ['c', 'm', 'y', 'k'],
                    lw = [1, 2, 3, 4])

and it's a little neater (e.g. compared to this one), you don't need to import cycler.

南城追梦 2024-12-17 13:26:06

正如 @jasmit 所提到的,在 matplotlib 3.7 中不需要导入循环。这是一个完整的示例:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_prop_cycle(color = ['c', 'm', 'y', 'k'],
                  ls    = ["-","--","-.",":"],
                  lw    = [1, 2, 3, 4])
for i in range(5):
    x = range(i,i+5)
    plt.plot(range(5),x)
    plt.legend(['No.1','No. 2','No. 3','No. 4','No. 5'])
plt.show()

在此处输入图像描述

As is mentioned by @jasmit, you do not need import cycle in matplotlib 3.7. Here is a complete example:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_prop_cycle(color = ['c', 'm', 'y', 'k'],
                  ls    = ["-","--","-.",":"],
                  lw    = [1, 2, 3, 4])
for i in range(5):
    x = range(i,i+5)
    plt.plot(range(5),x)
    plt.legend(['No.1','No. 2','No. 3','No. 4','No. 5'])
plt.show()

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文