通过python画三维图

对于新手,写一个用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图

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值