【问题标题】:Creating Matplotlib Graph with common line across subplots in Python在 Python 中使用跨子图的公共线创建 Matplotlib 图形
【发布时间】:2014-04-03 14:22:26
【问题描述】:

对于即将到来的任务,我需要制作一系列图表,其中包含两个图表,其中一条线从一个图表穿过另一个图表,并在另一个图表上为该线下方的区域着色。

如下图所示:

这是我目前拥有的:

从此代码:

from matplotlib import pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.plot([0,1,2,3,4,5,6,7,8,9,10], [1,1,1,1,1,0,0,0,0,0,0], '-b')
ax1.plot([0,1,2,3,4,5,6,7,8,9,10], [0,0,0,0,0,1,1,1,1,1,1], '-r')
ax1.set_ylim([0, 1.2])

ax2 = fig.add_subplot(122)
ax2.plot([0,5,10,15,20,25,30,35,40], [1,1,1,1,0,0,0,0,0], '-b')
ax2.plot([0,5,10,15,20,25,30,35,40], [0,0,0,0,1,1,1,1,1], '-r')
ax2.set_ylim([0, 1.2])

plt.show()

显然这只会生成两个图表,我还无法在两个图表之间添加线。

我真的希望能够在 python 中使用 Matplotlib 来执行此操作,并且能够更改值(在示例中为 45)并且颜色区域会自动更改。

谢谢!

【问题讨论】:

  • 到目前为止你尝试过什么代码?
  • 欢迎来到 Stack Overflow!看起来您希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只会在发布者已经尝试自己解决问题时提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出和您实际获得的输出(控制台输出、堆栈跟踪、编译器错误 - 不管是什么适用的)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask

标签: python graph matplotlib


【解决方案1】:

分三个步骤: 1、在左侧面板中找到绿线和蓝线之间的交点。 2nd,在右侧面板中找到红色和线条之间的截点。 3、填充中间的区域。这些步骤涉及到np.interpscipy.interpolatscipy.optimizeplt.fill_between,你应该查一下。

from matplotlib import pyplot as plt
import numpy as np
import scipy.interpolate as spinp
import scipy.optimize as spop

fig = plt.figure(figsize=(16,4))
ax1 = fig.add_subplot(121)
x  = [0,10,20,30,40,50,60,70,80,90,100]
yr = [1,1,1,1,1,0,0,0,0,0,0]
yg = [0,0,0,0,0,1,1,1,1,1,1]
turn_pt = np.interp(45, x, yr) #change 45 to whatever.
yb = [0.,turn_pt,turn_pt]
ax1.plot(x, yr, '-r')
ax1.plot(x, yg, '-g')
xb = [45, 45, 200]
ll = plt.plot(xb,yb, '-b')
ll[0].set_clip_on(False) 
plt.axis([0,100,0,1.2])
#the above three lines to draw the line out of the box.

ax2 = fig.add_subplot(122)
yr = [1,1,1,1,0,0,0,0,0]
yg = [0,0,0,0,1,1,1,1,1]
x  = [0,5,10,15,20,25,30,35,40]
brk_pt_f = lambda X, V: (spinp.interp1d(x, yr)(X)-V)**2
brk_pt = spop.fmin(brk_pt_f, 17., args=(turn_pt,), disp=0) #17. is you inital guess,
#the above two lines solve for the intersection between the blue line and the red line
zero_pt = 20.
start_pt= 0.
xb = np.hstack((start_pt, brk_pt, zero_pt))
yb = [turn_pt,turn_pt,0]
ax2.plot(x, yr, '-r')
ax2.plot(x, yg, '-g')
ax2.plot(xb, yb, '-b')
ax2.hlines(turn_pt,0, 40, 'b', alpha=0.)
ax2.fill_between(xb, yb, 0, alpha=0.4)
ax2.set_ylim([0, 1.2])
ax2.set_xlim([0, 40])

有一些解决方案可以摆脱顶部 x 轴和右侧 y 轴,请搜索较早的 SO 帖子。

最后,欢迎来到 SO。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多