[英]Matplotlib: combine different lines into a single object to be plotted many times
在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)")
编辑
汤姆的答案很好地解决了我的问题,建立在我上面的尝试的基础上(即,在一个数组中并列)。 任何其他采用不同方法的解决方案仍然欢迎您学习新的知识(例如,是否可以构建单个matplotlib对象( Artist
左右)?)。
如果您只想用一种方法绘制a
, b
和c
,则可以执行以下操作:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.