This is what I have so far. I want the code to fill between 1 and 2 on the y axis and stop along the function line. I have tried putting the function into the list of parameters but it doesn't work.
Qd = 2000 * P ** (-0.75)
plt.figure(figsize=(7,7))
plt.plot(Qd, P, label="demand")
plt.xlabel("quantity (Q)")
plt.ylabel("price (P)")
plt.grid()
plt.legend()
plt.title("Consumer Surplus")
plt.xlim([0, 3500])
plt.ylim([0, 5])
plt.fill_between([2000,0], [2, 2],1,
facecolor="blue",
color='blue',
alpha=0.2)
plt.show()
CodePudding user response:
So you can in principle work with fill_between
's where
argument and then call it twice, but I think the easiest solution is just to define some helper function where you basically pad the left side of P.
So I modified your code a little to achieve what you want. I also assumed, based on your settings for ylim
, that P runs from 0 to 5.
import matplotlib.pyplot as plt
import numpy as np
P = np.linspace(0, 5, 1000)
Qd = 2000 * P ** (-0.75)
plt.figure(figsize=(7,7))
plt.plot(Qd, P, label="demand")
plt.xlabel("quantity (Q)")
plt.ylabel("price (P)")
plt.grid()
plt.legend()
plt.title("Consumer Surplus")
plt.xlim([0, 3500])
plt.ylim([0, 5])
upper_bound = 2
lower_bound = 1
Pmin = np.argmax(P > lower_bound)
Pmax = np.argmax(P > upper_bound)
helper_P = np.append(P[Pmin:Pmax], upper_bound)
helper_Qd = np.append(Qd[Pmin:Pmax], 0)
plt.fill_between(helper_Qd, helper_P, lower_bound, color='blue', alpha=0.2)
plt.show()