Matplotlib:将不同的行组合成一个对象,以便多次绘制

时间:2015-06-23 10:07:21

标签: python matplotlib

matplotlib中,我怎样才能将一系列XY值(例如每个在数组或列表中)组合在一起多次绘制(与其他元素一起使用,这是一般的模式要绘制哪些不同的东西)?

我想计算/提取它们一次,然后将它们组合成一个对象/形状,以便在一个命令中正确绘制,而不是总是分别绘制它们:

import matplotlib.pyplot as plt
import numpy

# Simple example
numpy.random.seed(4)
x = range(10)
y = numpy.random.rand(10)

# Create three 'lines' (here, as x-y arrays) with different lenghts
a = numpy.array((x, y*10)).T
b = numpy.array((x[:5]*y[:5], y[:5]**2)).T
c = numpy.array((x[3:7], x[3:7])).T

# Combine a, b, and c in one object to be called many times later
# (this is not a good way to do that)
abc = numpy.concatenate((a, b, c))

# Plot
fig = plt.figure(figsize=(9,3))

ax0 = fig.add_subplot(131)
ax0.plot(a[:,0], a[:,1], color='b')
ax0.plot(b[:,0], b[:,1], color='r')
ax0.plot(c[:,0], c[:,1], color='g')
ax0.set_title("3 lines to be combined")

ax1 = fig.add_subplot(132)
ax1.plot(a[:,0], a[:,1], color='b')
ax1.plot(b[:,0], b[:,1], color='b')
ax1.plot(c[:,0], c[:,1], color='b')
ax1.set_title("Desired output")

ax2 = fig.add_subplot(133)
ax2.plot(abc[:,0], abc[:,1], color='b') # 1-line command
ax2.set_title("Wrong (spaghetti plot)")

enter image description here

编辑

汤姆的回答很好地解决了我的问题,建立在我上面的尝试上(即,在单个数组中进行连接)。任何其他具有不同方法的解决方案仍然欢迎学习新的东西(例如,是否可以构建单个matplotlib对象(Artist左右)?)。

1 个答案:

答案 0 :(得分:2)

如果你想要的只是一种方式来绘制abc,你可以这样做:

ax2.plot(a[:,0], a[:,1], b[:,0], b[:,1], c[:,0], c[:,1], color='b')

修改

要使用在原始对象之间仍有换行符的单个对象,可以使用numpy.NaN来破坏该行。

import matplotlib.pyplot as plt
import numpy

# Simple example
numpy.random.seed(4)
x = range(10)
y = numpy.random.rand(10)

# Create three 'lines' (here, as x-y arrays) with different lenghts
a = numpy.array((x, y*10)).T
b = numpy.array((x[:5]*y[:5], y[:5]**2)).T
c = numpy.array((x[3:7], x[3:7])).T

# Use this to break up the original objects. 
# plt.plot does not like NaN's, so will break the line there.
linebreak=[[numpy.NaN,numpy.NaN]]

# Combine a, b, and c in one object to be called many times later
abc = numpy.concatenate((a, linebreak, b, linebreak, c))

# Plot
fig = plt.figure(figsize=(9,3))

ax0 = fig.add_subplot(131)
ax0.plot(a[:,0], a[:,1], color='b')
ax0.plot(b[:,0], b[:,1], color='r')
ax0.plot(c[:,0], c[:,1], color='g')
ax0.set_title("3 lines to be combined")

ax1 = fig.add_subplot(132)
ax1.plot(a[:,0], a[:,1], color='b')
ax1.plot(b[:,0], b[:,1], color='b')
ax1.plot(c[:,0], c[:,1], color='b')
ax1.set_title("Desired output")

ax2 = fig.add_subplot(133)
ax2.plot(abc[:,0], abc[:,1], color='b') # 1-line command
ax2.set_title("Single object with breaks")

enter image description here