用Python和Matplotlib手把手教你绘制需求曲线(附完整代码与经济学原理)

张开发
2026/4/21 8:26:27 15 分钟阅读

分享文章

用Python和Matplotlib手把手教你绘制需求曲线(附完整代码与经济学原理)
用Python和Matplotlib手把手教你绘制需求曲线附完整代码与经济学原理在数据驱动的时代将抽象的经济学概念转化为直观的可视化图表是每个技术型经济学爱好者必备的技能。想象一下当你能够用几行代码就展现出价格变动如何影响消费者行为或者用动态图表演示市场供需关系时那些枯燥的理论突然变得生动起来。这正是Python在经济学领域大放异彩的地方——它不仅是数据科学家的利器也正在成为现代经济学研究的新工具。对于程序员和数据分析师来说经济学原理可能显得有些抽象而编程又可能让经济学背景的学习者望而生畏。本文将打破这种隔阂带你从零开始用Python中最流行的可视化库Matplotlib一步步构建专业级的需求曲线图表。我们不仅会关注代码实现更会深入探讨每一行代码背后的经济学含义让你真正理解为什么要这样画而不仅仅是怎么画。1. 环境准备与基础概念在开始编码之前我们需要确保开发环境配置正确并重温一些关键的经济学概念。Python 3.6及以上版本都能很好地运行我们将要编写的代码推荐使用Jupyter Notebook进行交互式开发这对数据分析和可视化特别友好。首先安装必要的库pip install matplotlib numpy pandas需求曲线是经济学中最基础也最重要的工具之一它描述了在其他条件不变的情况下商品价格与需求量之间的关系。典型的线性需求函数可以表示为Qd α - β·P其中Qd 代表需求量P 代表价格α 是需求曲线在数量轴上的截距价格为零时的需求量β 表示需求曲线斜率的绝对值注意经济学中通常将价格(P)放在纵轴数量(Q)放在横轴这与数学中的习惯相反需要特别注意。让我们先用NumPy创建一个简单的需求函数import numpy as np def demand_function(prices, alpha1000, beta20): 线性需求函数 return alpha - beta * prices这个函数接受价格数组返回对应的需求量。α1000意味着当商品免费时需求量将达到1000单位β20表示价格每增加1元需求量会减少20单位。2. 绘制基础需求曲线有了需求函数我们就可以开始绘制第一条需求曲线了。Matplotlib提供了高度灵活的API可以创建出版质量的图表。import matplotlib.pyplot as plt # 创建价格区间 prices np.linspace(0, 50, 100) # 从0到50元的100个均匀分布价格点 quantities demand_function(prices) # 创建图表 plt.figure(figsize(10, 6)) plt.plot(quantities, prices, label需求曲线, colorblue, linewidth2) # 添加标签和标题 plt.xlabel(需求量 (Q), fontsize12) plt.ylabel(价格 (P), fontsize12) plt.title(基础线性需求曲线, fontsize14) plt.grid(True, linestyle--, alpha0.6) plt.legend() plt.show()这段代码会生成一条从左上方向右下方倾斜的直线完美展现了价格与需求量之间的反向关系。图表中的几个关键元素坐标轴标签按照经济学惯例价格在纵轴数量在横轴网格线虚线网格提高了图表的可读性线条样式2像素宽的蓝色实线清晰可见为了更专业地展示我们可以添加一些经济学图表常见的元素plt.figure(figsize(10, 6)) plt.plot(quantities, prices, label需求曲线 D, colorblue, linewidth2) # 添加关键点标记 max_price np.max(prices) max_q_at_zero_price demand_function(0) plt.scatter([0], [max_price], colorred, zorder5) plt.scatter([max_q_at_zero_price], [0], colorred, zorder5) # 添加坐标轴箭头 plt.gca().spines[right].set_visible(False) plt.gca().spines[top].set_visible(False) plt.gca().spines[left].set_position(zero) plt.gca().spines[bottom].set_position(zero) # 添加标注 plt.annotate(f({max_q_at_zero_price}, 0), xy(max_q_at_zero_price, 0), xytext(10, 10), textcoordsoffset points) plt.annotate(f(0, {max_price}), xy(0, max_price), xytext(10, 10), textcoordsoffset points) plt.xlabel(需求量 (Q), fontsize12) plt.ylabel(价格 (P), fontsize12) plt.title(专业经济学风格需求曲线, fontsize14) plt.legend() plt.show()3. 非线性需求曲线与弹性分析现实世界中的需求关系往往不是简单的线性关系。让我们探讨更复杂的非线性需求曲线及其经济学含义。考虑一个非线性需求函数Qd α·P^(-β)这个幂函数形式的需求关系在经济学中很常见其中价格弹性不再是常数。我们可以这样实现def nonlinear_demand(prices, alpha1000, beta0.5): 非线性需求函数 return alpha * (prices ** (-beta)) prices np.linspace(1, 50, 100) # 从1开始避免除以零 quantities nonlinear_demand(prices) plt.figure(figsize(10, 6)) plt.plot(quantities, prices, label非线性需求曲线, colorgreen, linewidth2) # 计算并标注弹性 def price_elasticity(p, q, alpha, beta): 计算价格弹性 return -beta # 对于这个特定函数弹性恒为-β elasticity price_elasticity(prices, quantities, 1000, 0.5) plt.annotate(f价格弹性 -{elasticity[0]:.1f} (单位弹性), xy(quantities[20], prices[20]), xytext(30, -30), textcoordsoffset points, arrowpropsdict(arrowstyle-)) plt.xlabel(需求量 (Q), fontsize12) plt.ylabel(价格 (P), fontsize12) plt.title(非线性需求曲线与价格弹性, fontsize14) plt.grid(True, linestyle--, alpha0.6) plt.legend() plt.show()非线性需求曲线展示了价格弹性如何随价格水平变化。在我们的例子中弹性恒为-0.5意味着价格每上涨1%需求量下降0.5%这属于缺乏弹性的需求。为了更全面地理解不同价格点的弹性变化我们可以创建一个弹性计算表价格区间需求量变化价格变化弹性系数弹性类型10-15元-12%50%-0.24缺乏弹性15-20元-10%33%-0.30缺乏弹性20-25元-9%25%-0.36缺乏弹性25-30元-8%20%-0.40缺乏弹性4. 需求曲线的移动与旋转需求曲线并非一成不变当除价格外的其他因素变化时整个曲线会发生移动或旋转。让我们用代码模拟这些变化。需求曲线平移收入变化或替代品价格变化# 原始需求 prices np.linspace(0, 50, 100) original_demand demand_function(prices) # 需求增加收入增加或替代品价格上涨 demand_increase demand_function(prices, alpha1200, beta20) # 需求减少收入减少或互补品价格上涨 demand_decrease demand_function(prices, alpha800, beta20) plt.figure(figsize(10, 6)) plt.plot(original_demand, prices, label原始需求 D0, colorblue) plt.plot(demand_increase, prices, label需求增加 D1, colorgreen) plt.plot(demand_decrease, prices, label需求减少 D2, colorred) plt.xlabel(需求量 (Q), fontsize12) plt.ylabel(价格 (P), fontsize12) plt.title(需求曲线的平移, fontsize14) plt.grid(True, linestyle--, alpha0.6) plt.legend() plt.show()需求曲线旋转消费者偏好变化或价格预期变化# 需求弹性变大β减小 more_elastic demand_function(prices, alpha1000, beta10) # 需求弹性变小β增大 less_elastic demand_function(prices, alpha1000, beta30) plt.figure(figsize(10, 6)) plt.plot(original_demand, prices, label原始需求 D0, colorblue) plt.plot(more_elastic, prices, label弹性更大 D1, colorpurple) plt.plot(less_elastic, prices, label弹性更小 D2, colororange) plt.xlabel(需求量 (Q), fontsize12) plt.ylabel(价格 (P), fontsize12) plt.title(需求曲线斜率的改变, fontsize14) plt.grid(True, linestyle--, alpha0.6) plt.legend() plt.show()理解这些变化对于实际商业决策至关重要。例如当竞争对手的产品涨价时你的产品需求曲线会向右移动当消费者偏好转向你的产品时曲线不仅会移动弹性也可能发生变化。5. 交互式需求曲线与市场模拟静态图表虽然有用但交互式可视化能带来更深入的理解。我们将使用Matplotlib的交互功能创建一个简单的需求曲线探索工具。from matplotlib.widgets import Slider # 创建图形和轴 fig, ax plt.subplots(figsize(10, 6)) plt.subplots_adjust(bottom0.25) # 为滑块留出空间 # 初始参数 initial_alpha 1000 initial_beta 20 # 绘制初始需求曲线 prices np.linspace(0, 50, 100) line, ax.plot(demand_function(prices, initial_alpha, initial_beta), prices, lw2) # 添加滑块 ax_alpha plt.axes([0.25, 0.1, 0.65, 0.03]) ax_beta plt.axes([0.25, 0.05, 0.65, 0.03]) slider_alpha Slider(ax_alpha, α (截距), 500, 1500, valinitinitial_alpha) slider_beta Slider(ax_beta, β (斜率), 5, 50, valinitinitial_beta) # 更新函数 def update(val): current_alpha slider_alpha.val current_beta slider_beta.val line.set_xdata(demand_function(prices, current_alpha, current_beta)) fig.canvas.draw_idle() # 注册更新函数 slider_alpha.on_changed(update) slider_beta.on_changed(update) # 设置图表属性 ax.set_xlabel(需求量 (Q)) ax.set_ylabel(价格 (P)) ax.set_title(交互式需求曲线探索) ax.grid(True) plt.show()这个交互式工具允许你实时调整需求函数的参数立即看到曲线如何变化。尝试以下操作增加α值观察曲线如何向右平移增加β值观察曲线如何变得更陡峭弹性变小寻找使曲线通过特定价格-数量组合的参数组合6. 需求曲线的实际应用案例让我们看一个实际应用场景假设你经营一家咖啡店想确定最优定价策略。通过市场调研你估计需求函数参数大致为α120β4价格单位为美元。# 咖啡店需求函数 def coffee_demand(prices, alpha120, beta4): return alpha - beta * prices prices np.linspace(0, 30, 100) quantities coffee_demand(prices) # 计算总收入 revenue prices * quantities # 找到收入最大化的价格 max_revenue_idx np.argmax(revenue) optimal_price prices[max_revenue_idx] optimal_quantity quantities[max_revenue_idx] # 绘制需求曲线和收入曲线 fig, ax1 plt.subplots(figsize(10, 6)) color tab:blue ax1.set_xlabel(需求量 (杯/天)) ax1.set_ylabel(价格 ($), colorcolor) ax1.plot(quantities, prices, colorcolor, label需求曲线) ax1.scatter([optimal_quantity], [optimal_price], colorred, zorder5) ax1.annotate(f最优价格: ${optimal_price:.2f}\n销量: {int(optimal_quantity)}杯, xy(optimal_quantity, optimal_price), xytext(10, 10), textcoordsoffset points) ax1.tick_params(axisy, labelcolorcolor) # 添加收入曲线 ax2 ax1.twinx() color tab:orange ax2.set_ylabel(收入 ($), colorcolor) ax2.plot(quantities, revenue, colorcolor, linestyle--, label收入曲线) ax2.scatter([optimal_quantity], [revenue[max_revenue_idx]], colorred, zorder5) ax2.tick_params(axisy, labelcolorcolor) plt.title(咖啡店需求分析与收入最大化定价, fontsize14) fig.tight_layout() plt.show()这个分析显示当定价为15美元时每天能卖出60杯总收入达到最大的900美元。高于或低于这个价格都会导致总收入下降。当然实际决策还需要考虑成本因素但这已经提供了一个很好的起点。7. 高级技巧需求曲线的三维可视化当我们需要考虑多个变量对需求的影响时三维可视化就非常有用了。例如同时展示价格和收入对需求量的影响。from mpl_toolkits.mplot3d import Axes3D # 创建网格 price_values np.linspace(1, 20, 50) income_values np.linspace(20000, 80000, 50) P, I np.meshgrid(price_values, income_values) # 需求函数Q a - b*P c*I a, b, c 50, 2, 0.001 Q a - b*P c*I # 创建3D图形 fig plt.figure(figsize(12, 8)) ax fig.add_subplot(111, projection3d) # 绘制曲面 surf ax.plot_surface(Q, P, I, cmapviridis, alpha0.8) # 添加标签 ax.set_xlabel(需求量 (Q)) ax.set_ylabel(价格 (P)) ax.set_zlabel(收入 (I)) ax.set_title(价格与收入对需求量的联合影响, fontsize14) # 添加颜色条 fig.colorbar(surf, shrink0.5, aspect5, label收入水平) plt.tight_layout() plt.show()这个三维图表清晰地展示了在任一固定收入水平下价格与需求量呈负相关需求曲线向下倾斜在任一固定价格下收入与需求量呈正相关收入增加使需求曲线右移收入效应在高价格区域更为明显在实际项目中我发现这种三维可视化特别适合向非技术背景的决策者解释复杂的关系。旋转视图功能让他们可以从不同角度理解这些经济关系效果远胜于静态图表或口头解释。

更多文章