python数据可视化实验:绘制3D图表

1.绘制一个具有动画效果的图表,要求如下:

(1) 绘制一条正弦曲线;
(2) 绘制一个红色圆点,该圆点最初位于正弦曲线的左端;
(3) 制作一个圆点沿曲线运动的动画,并时刻显示圆点的坐标位置。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 指定渲染环境
%matplotlib qt5
def update_points(num):
    '''更新数据点'''
    #设置图像上移动的点
    point_ani.set_data(x[num], y[num])
    #设置点坐标文本
    text_pt.set_text("x=%.3f, y=%.3f"%(x[num], y[num]))
    return point_ani, text_pt
#创建数值序列
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
#创建画布,并自动调整子图位置
fig = plt.figure(tight_layout=True)
plt.plot(x, y)
point_ani, = plt.plot(x[0], y[0], marker="o",markerfacecolor="red")
#设置坐标文本
text_pt = plt.text(4, 0.9, '', fontsize=15)
#设置动画
ani = animation.FuncAnimation(fig=fig, func=update_points, frames=np.arange(0, 100),interval=100, blit=True)
plt.show()

运行结果(只截取了动态图的其中一部分):

2. 请在一个3D坐标系内绘制一个球体。 

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
#生成球体的数据
t = np.linspace(0, np.pi * 2, 100)
s = np.linspace(0, np.pi, 100)
#生成三维网格
t, s = np.meshgrid(t, s)
x = np.cos(t) * np.sin(s)
y = np.sin(t) * np.sin(s)
z = np.cos(s)
# 创建三维坐标系的绘图区域
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
#绘制曲面图
ax.plot_surface(x, y, z,color="orange")
ax.set_xlabel('x轴') #x轴名称
ax.set_ylabel('y轴') #y轴名称
ax.set_zlabel('z轴') #z轴名称
plt.show()

3.利用excel保存某公司2022年不同产品销售记录,请读取并统计不少于5种产品每个月的销售总额,选取合适图表在3D坐标系中展示

import numpy as np 
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False

df = pd.read_excel("F:/DaiMa/MyJupyter/data/company.xlsx")
newdf=df.set_index('产品')#将产品列改为索引
#display(newdf)
x = np.arange(0,5,step=1)#x轴的坐标
y = np.arange(0,12,step=1)#y轴的坐标
z=np.zeros(shape=(5, 12))
#print(newdf.iloc[0,0])
for i in range(5):
    for j in range(12):
        z[i,j]=newdf.iloc[i,j]
        #print(z[i,j])

xx,yy=np.meshgrid(x,y)#网格化坐标
x, y=xx.ravel(), yy.ravel()#矩阵扁平化
bottom=np.zeros_like(x)#设置柱状图的底端位值
z=z.ravel()#扁平化矩阵

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.bar3d(x,y,bottom,dx=1,dy=1,dz=z,shade=True)

ax.set_xticks([0,1,2,3,4])
ax.set_xticklabels(newdf.index)
ax.set_yticks([1,2,3,4,5,6,7,8,9,10,11,12])
#print(newdf.columns)
ax.set_yticklabels(newdf.columns,fontsize=6)
plt.show()

运行结果:

4.查找10个省份近十年的GDP数据,利用 animation 制作各省份GDP由高到低排序动态变化图 

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# 读取数据
df = pd.read_csv('F:/DaiMa/MyJupyter/data/gdp.csv')


# 将province改成索引列,并排序
newdf = df.set_index('Province').sort_values(by='2024', ascending=False)
#display(newdf)

# 创建画布和子图
fig, ax = plt.subplots()

# 设置初始状态
def init():
    ax.clear()#先清空
    ax.bar(newdf.index, newdf['2015'])
    ax.set_ylabel('GDP (亿元)')
    ax.set_title('2015年各省份GDP')
    plt.xticks(rotation=45, ha='right')
    #无指向注释
    # plt.text(a,b,b)数据显示的横坐标、显示的位置高度、显示的数据值的大小
    for a,b in zip(np.arange(10),newdf['2015']):
        ax.text(a,b,b,ha='center',va='bottom')

# 更新函数
def update(year):
    ax.clear()#先清空
    newdf2 = df.set_index('Province').sort_values(by=str(year), ascending=False)
    ax.bar(newdf2.index, newdf2[str(year)])
    ax.set_ylabel('GDP (亿元)')
    ax.set_title(f'{year}年各省份GDP')
    plt.xticks(rotation=45, ha='right')
    #无指向注释
    # plt.text(a,b,b)数据显示的横坐标、显示的位置高度、显示的数据值的大小
    for a,b in zip(np.arange(10),newdf2[str(year)]):
        ax.text(a,b,b,ha='center',va='bottom')

# 创建动画
ani = FuncAnimation(fig, update, frames=range(2015, 2025), init_func=init,interval=500)

# 展示动画
plt.show()

运行结果(只截取了动态图的其中一部分):

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值