[英]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.