[英]3d Surface plot from linear model with matplotlib in Python
[英]Plot linear model in 3d with Matplotlib
我正在嘗試創建適合數據集的線性模型的 3d 圖。 我能夠在 R 中相對輕松地做到這一點,但我真的很難在 Python 中做到這一點。 這是我在 R 中所做的:
這是我在 Python 中所做的:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as sm
csv = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
model = sm.ols(formula='Sales ~ TV + Radio', data = csv)
fit = model.fit()
fit.summary()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(csv['TV'], csv['Radio'], csv['Sales'], c='r', marker='o')
xx, yy = np.meshgrid(csv['TV'], csv['Radio'])
# Not what I expected :(
# ax.plot_surface(xx, yy, fit.fittedvalues)
ax.set_xlabel('TV')
ax.set_ylabel('Radio')
ax.set_zlabel('Sales')
plt.show()
我做錯了什么,我應該怎么做?
謝謝你。
知道了!
我在對 mdurant 的回答的評論中談到的問題是,表面沒有繪制成像這些Combining scatter plot with surface plot那樣漂亮的方形圖案。
我意識到問題出在我的meshgrid
,所以我更正了兩個范圍( x
和y
)並為np.arange
使用了比例步np.arange
。
這使我可以使用 mdurant 的答案提供的代碼,並且效果很好!
結果如下:
這是代碼:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as sm
from matplotlib import cm
csv = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
model = sm.ols(formula='Sales ~ TV + Radio', data = csv)
fit = model.fit()
fit.summary()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x_surf = np.arange(0, 350, 20) # generate a mesh
y_surf = np.arange(0, 60, 4)
x_surf, y_surf = np.meshgrid(x_surf, y_surf)
exog = pd.core.frame.DataFrame({'TV': x_surf.ravel(), 'Radio': y_surf.ravel()})
out = fit.predict(exog = exog)
ax.plot_surface(x_surf, y_surf,
out.reshape(x_surf.shape),
rstride=1,
cstride=1,
color='None',
alpha = 0.4)
ax.scatter(csv['TV'], csv['Radio'], csv['Sales'],
c='blue',
marker='o',
alpha=1)
ax.set_xlabel('TV')
ax.set_ylabel('Radio')
ax.set_zlabel('Sales')
plt.show()
您假設 plot_surface 想要使用坐標網格是正確的,但是 predict 想要一個數據結構,就像您所安裝的那樣(“exog”)。
exog = pd.core.frame.DataFrame({'TV':xx.ravel(),'Radio':yy.ravel()})
out = fit.predict(exog=exog)
ax.plot_surface(xx, yy, out.reshape(xx.shape), color='None')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.