我的数据框中包含许多线性方程,我想用Python绘制这些方程,方程采用这种格式,例如:
我如何自动执行此操作?
b = row['b']
λ1 = row['λ1']
λ2 = row['λ2']
restricao = row['Restrições']
if restricao == '<=':
# Se λ1 for zero
if λ1 == 0:
plt.plot([0, 0], [0, b / λ2], linestyle='solid')
# Se λ2 for zero
elif λ2 == 0:
plt.plot([b / λ1, 0], [0, 0], linestyle='solid')
# Se λ2 for zero
elif b == 0:
plt.plot([0, 0], [0, 0], linestyle='solid')
# Se ambos λ1 e λ2 são diferentes de zero
else:
plt.plot([b / λ1, 0], [0, b / λ2], linestyle='solid')
elif restricao == '>=':
# Se λ1 for zero
if λ1 == 0:
plt.plot([0, 0], [0, b / λ2], linestyle='solid')
# Se λ2 for zero
elif λ2 == 0:
plt.plot([b / λ1, 0], [0, 0], linestyle='solid')
# Se λ2 for zero
elif b == 0:
plt.plot([0, 0], [0, 0], linestyle='solid')
# Se ambos λ1 e λ2 são diferentes de zero
else:
plt.plot([b / λ1, 0], [0, b / λ2], linestyle='solid')
您可以使用
iterrows()
:
import pandas as pd
import matplotlib.pyplot as plt
def plot(df):
for _, row in df.iterrows():
b = row['b']
λ1 = row['λ1']
λ2 = row['λ2']
restricao = row['r']
if restricao in ['<=', '>', '=']:
if not λ1:
plt.plot([0, 0], [0, b / λ2], linestyle='solid')
elif not λ2:
plt.plot([b / λ1, 0], [0, 0], linestyle='solid')
elif not b:
plt.plot([0, 0], [0, 0], linestyle='solid')
else:
plt.plot([b / λ1, 0], [0, b / λ2], linestyle='solid')
plt.xlabel('x-axis')
plt.ylabel('y-axis label')
plt.title('Equations')
plt.grid(True)
plt.show()
df = pd.DataFrame({
'b': [-1.0, 1.0, 3.4],
'λ1': [2.0, -2.0, 3.0],
'λ2': [5.0, -3.0, 3.0],
'r': ['<=', '>', '=']
})
plot(df)