绘制多个Y值与X

2024-10-03 19:23:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我得画两张图表。问题是:

f1 = x1*(x2-1)
f2 = x1^2+x2^2

限制条件:

x2 <= x1
x1 <= x2*4
0 <= x1 <= 1
0 <= x2 <= 1

我必须在两张图表中画出所有可能的值。1-x1对x2;2-f1对f2。 对于限制x2<;=x1和x1<;=x2*4,我提出了x2<=x1<=x2*4,因此编写代码更容易。你知道吗

我试过创建一个小代码来创建x1和x2,但不幸的是没有成功。你知道吗

x1 = []
for n in range(1,1000,1):
   x1.append(n/1000) #Couldn't find a better solution to create a list between 0 and 1

pValues11 = []
for n in range(1,10000,1):
   pValues11.append(n/10000)

x2 = []
for index,n in enumerate(x1):
   x2.append([])
   for m in pValues11:
      if n <= m and m <= 4*n:
        x2[index].append(m)

x2创建一个列表列表,而x1就像一个索引。但是,如果我试图描绘它们:

plt.plot(x1,x2,'bo')
plt.show()

我收到ValueError: setting an array element with a sequence.

总而言之,我认为解决这个问题的方法很混乱,但是我不知道如何干净利落。你知道吗

结果应该是这样的,我同学的:

enter image description here


Tags: and代码inlt列表forindex图表
1条回答
网友
1楼 · 发布于 2024-10-03 19:23:35

以下是基于numpy的解决方案:

import numpy as np
import matplotlib.pyplot as plt

x1=np.linspace(0,1,1000)
x2=np.linspace(0,1,1000)[:,None]

#f1=x1*(x2-1)
#f2=x1**2+x2**2

inds=(x2<=x1) & (x1<=4*x2)

x1new=(x1+np.zeros(x2.shape))[inds]
x2new=(x2+np.zeros(x1.shape))[inds]
#f1new=f1[inds]
#f2new=f2[inds]
f1new=x1new*(x2new-1)
f2new=x1new**2+x2new**2

plt.figure()
plt.scatter(x1new,x2new)
plt.xlabel(r"$x_1$")
plt.ylabel(r"$x_2$")

plt.figure()
plt.scatter(f1new,f2new)
plt.xlabel(r"$f_1$")
plt.ylabel(r"$f_2$")

plt.show()

这实际上会生成一个x1x2值的2d网格,然后根据条件检查每一对。那些测试失败的将被丢弃,因此我们只保留正确的x1x2f1f2值。然后我们就把它们画出来。你知道吗

我的输出:

x2 vs x1f2 vs f1

您的预期输出:

expected

差异产生于这样一个事实,即预期的输出被标绘到x2=0.5,而我使用了到x2=1的完整范围。你知道吗

相关问题 更多 >