对于新手,写一个用python画三维图,基本的功能都有了,具体代码可以参考如下:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mlp
from matplotlib.font_manager import fontManager
import requests
import numpy as np
from ipywidgets import interact
fontManager.addfont("ChineseFont.ttf")
mlp.rc('font', family="ChineseFont") # 防止显示中文乱码
res = requests.get("http://www.shijie500qiang.com/news/587.html") #网页地址
res.encoding = 'utf-8' # 设置字体编码,防止读出来的中文是乱码
html = res.text
df = pd.read_html(html) # 读取内容
data = df[0].head(71) # 读取71行数据
x = data["时间(年)"].sort_values() # 读取“时间(年)”这一列数据,并做倒序
y = data["人口(亿)"].sort_values() # 读取“人口(亿)”这一列数据,并做倒序
def compute_cost(x, y, w, b):
y_pred = (np.array(list(map(int, x))) - 1949) * w + b
cost = (y - y_pred) ** 2
cost = cost.sum() / len(x)
return cost
def print_3d():
ws = np.arange(0, 0.2, 0.01)
bs = np.arange(0, 10, 0.1)
costs = np.zeros((20, 100))
i = 0
for w in ws:
j = 0
for b in bs:
cost = compute_cost(x, y, w, b)
costs[i, j] = cost
j += 1
i += 1
plt.figure(figsize=(10, 10)) # 设置3D图的大小
ax = plt.axes(projection = "3d") # 创建一个3D图
ax.view_init(45, -120) # 3D图的视角角度
ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) # 将3D坐标区的背景设置为白色
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) # 将3D坐标区的背景设置为白色
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) # 将3D坐标区的背景设置为白色
b_grid, w_grid = np.meshgrid(bs, ws)
ax.plot_surface(w_grid, b_grid, costs, cmap="Spectral_r", alpha = 0.7) # 绘制一个Spectral_r类型的抛物面,并对其设置透明度,w_grid为x轴值,b_grid为y轴值,costs为z轴值
ax.plot_wireframe(w_grid, b_grid, costs, color = "black", alpha = 0.1) # 绘制3D线框图,线条颜色为黑色,并设置透明度,w_grid为x轴值,b_grid为y轴值,costs为z轴值
ax.set_title("time-number") # 3D图的标题
ax.set_xlabel("time") # 3D图的x轴名称
ax.set_ylabel("number") # 3D图的y轴名称
ax.set_zlabel("COST") # 3D图的z轴名称
w_index, b_index = np.where(costs == np.min(costs))
ax.scatter(ws[w_index], bs[b_index], costs[w_index, b_index], color = "red", s = 40) # 在3D图上画一个红色的坐标点
plt.show() # 把图显示出来
print_3d()
大家可以自己运行一下,具体我把画三维图的接口说明都写在代码后面的注释里。运行结果如下:
python画的3d图