GVKun编程网logo

使用matplotlib的3D动画(matplotlib 3d动画)

23

如果您对使用matplotlib的3D动画和matplotlib3d动画感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解使用matplotlib的3D动画的各种细节,并对matplotlib3d

如果您对使用matplotlib的3D动画matplotlib 3d动画感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解使用matplotlib的3D动画的各种细节,并对matplotlib 3d动画进行深入的分析,此外还有关于ImportError:未安装带有matplotlib的名为matplotlib的模块、java版matplotlib,matplotlib4j使用,java中调用matplotlib或者其他python脚本、Matplotlib 3D散点动画、Matplotlib Toolkits:三维绘图工具包 matplotlib.mplot3d的实用技巧。

本文目录一览:

使用matplotlib的3D动画(matplotlib 3d动画)

使用matplotlib的3D动画(matplotlib 3d动画)

我想用matplotlib制作3D动画,但是我不知道该怎么做。这是我的无效代码。

from matplotlib import pyplot as pltimport numpy as npfrom mpl_toolkits.mplot3d import Axes3Dfrom matplotlib import animationfrom math import *fig = plt.figure()ax = fig.add_subplot(111) #, projection=''3d''#settingax.set_xlim(-5,5)ax.set_ylim(-5,5)#ax.set_zlim(-5,5)ax.set_xlabel(''x'')ax.set_ylabel(''y'')#ax.set_zlabel(''z'')ax.grid()f1, = ax.plot([], [], "r-", lw=1) #plot1def gen():    for phi in np.linspace(0,2*pi,100):        yield np.cos(phi), np.sin(phi), phidef update(data):    p1, q1, psi = data    f1.set_data(p1,q1)    #f1.set_3d_properties(psi)ani = animation.FuncAnimation(fig, update, gen, blit=False, interval=100, repeat=True)#ani.save(''matplot003.gif'', writer=''imagemagick'')plt.show()

答案1

小编典典

我使用了以下示例http://matplotlib.org/1.4.1/examples/animation/simple_3danim.html
并修改了您的代码:

from matplotlib import pyplot as pltimport numpy as npimport mpl_toolkits.mplot3d.axes3d as p3from matplotlib import animationfig = plt.figure()ax = p3.Axes3D(fig)def gen(n):    phi = 0    while phi < 2*np.pi:        yield np.array([np.cos(phi), np.sin(phi), phi])        phi += 2*np.pi/ndef update(num, data, line):    line.set_data(data[:2, :num])    line.set_3d_properties(data[2, :num])N = 100data = np.array(list(gen(N))).Tline, = ax.plot(data[0, 0:1], data[1, 0:1], data[2, 0:1])# Setting the axes propertiesax.set_xlim3d([-1.0, 1.0])ax.set_xlabel(''X'')ax.set_ylim3d([-1.0, 1.0])ax.set_ylabel(''Y'')ax.set_zlim3d([0.0, 10.0])ax.set_zlabel(''Z'')ani = animation.FuncAnimation(fig, update, N, fargs=(data, line), interval=10000/N, blit=False)#ani.save(''matplot003.gif'', writer=''imagemagick'')plt.show()

ImportError:未安装带有matplotlib的名为matplotlib的模块

ImportError:未安装带有matplotlib的名为matplotlib的模块

代码行:

import matplotlib

错误:

ImportError:没有名为“ matplotlib”的模块

问题:

which python3.4    % /usr/bin/python3.4

matplotlib在哪里安装?

sudo find /usr | grep matplotlib  % /usr/lib/pymodules/python2.7/matplotlib/...

一些注意事项:

  • 操作系统:Linux Mint 17.2
  • 我需要使用Python 3.4

解决方案:

  • import sys sys.path.append(''/usr/lib/pymodules/python2.7/'') (对此不满意)。

  • 使用pip3 install matplotlibsudo pip3 install matplotlib(接收错误,我也不喜欢这一点)。

  • 使用sudo apt-get install python-matplotlib(可能是完美的选择,但在python2.7目录中安装了matplotlib)。

我如何使Matplotlib适用于python3?谢谢

答案1

小编典典

就在我要提出这个问题的时候意识到

sudo apt-get install python-matplotlib

我需要输入

sudo apt-get install python3-matplotlib

java版matplotlib,matplotlib4j使用,java中调用matplotlib或者其他python脚本

java版matplotlib,matplotlib4j使用,java中调用matplotlib或者其他python脚本

写在前面,最近需要在java中调用matplotlib,其他一些画图包都没这个好,毕竟python在科学计算有优势。找到了matplotlib4j,大概看了下github上的https://github.com/sh0nk/matplotlib4j,maven repository:

<dependency>
   <groupId>com.github.sh0nk</groupId>
       <artifactId>matplotlib4j</artifactId>
       <version>0.5.0</version>
</dependency>

简单贴个测试类,更多的用法在test报下有个MainTest.class。

 @Test
    public void testPlot() throws IOException, PythonExecutionException, ClassNotFoundException, NoSuchMethodException, illegalaccessexception, InvocationTargetException, InstantiationException {
        Plot plot = Plot.create(PythonConfig.pythonBinPathConfig("D:\\python3.6\\python.exe"));
        plt.plot()
                .add(Arrays.asList(1.3, 2))
                .label("label")
                .linestyle("--");
        plt.xlabel("xlabel");
        plt.ylabel("ylabel");
        plt.text(0.5, 0.2, "text");
        plt.title("Title!");
        plt.legend();
        plt.show();

    }

下面问题来了,这个对matplotlib的封装不是很全面,源码里也有很多todo,有很多函数简单用用还行,很多重载用不了,比如plt.plot(xdata,ydata)可以,但是无法在其中指定字体plt.plot(xdata,ydata,fontsize=30);

所以想要更全面的用法还得自己动手,几种办法:

  1. 大部分还是用matplotlib4j中的,个别的自己需要的但里头没有的函数,实现他的builder接口,重写build方法,返回一个py文件中命令行的字符串形式,然后反射取到PlotImpl中的成员变量registeredBuilders,往后追加命令行,感觉适用于只有极个别命令找不到的情况,挺麻烦的,而且要是传nd.array(…)这种参数还得额外拼字符串。
//拿到plotImpl中用于组装python脚本语句的的registeredBuilders,需要加什么直接添加新的builder就行了
        Field registeredBuildersField = plt.getClass().getDeclaredField("registeredBuilders");
        registeredBuildersField.setAccessible(true);
        List<Builder> registeredBuilders = (List<Builder>) registeredBuildersField.get(plt);

        TicksBuilder ticksBuilder = new TicksBuilder(yList, "yticks", fontSize);
        registeredBuilders.add(ticksBuilder);
  1. 这种比较直接,参照matplotlib4j底层,直接写py.exe文件,执行命令行,比较推荐这种,一行一行脚本自己写,数据拼装方便,看起来直观。比如写如下的脚本并执行,搞两组数据,画个散点图
import numpy as np
import matplotlib.pyplot as plt
plt.plot(np.array(自己的x数据), np.array(自己的y数据), 'k.', markersize=4)
plt.xlim(0,6000)
plt.ylim(0,24)
plt.yticks(np.arange(0, 25, 1), fontsize=10)
plt.title("waterfall")
plt.show()

像下面这么写就行了

		//1. 准备自己的数据 不用管
        List<Float> y_secondList_formatByHours = y_secondList.stream().map(second -> (float)second / 3600).collect(Collectors.toList());

        //2.准备命令行list,逐行命令添加
        List<String> scriptLines = new ArrayList<>();
        scriptLines.add("import numpy as np");
        scriptLines.add("import matplotlib.pyplot as plt");
        scriptLines.add("plt.plot("+"np.array("+x_positionList+"),"+"np.array(" +y_secondList_formatByHours+"),\"k.\",label=\"waterfall\",lw=1.0,markersize=4)");
        scriptLines.add("plt.xlim(0,6000)");
        scriptLines.add("plt.ylim(0,24)");
        scriptLines.add("plt.yticks(np.arange(0, 25, 1), fontsize=10)");
        scriptLines.add("plt.title(\"waterfall\")");
        scriptLines.add("plt.show()");
        //3. 调用matplotlib4j 里面的pycommond对象,传入自己电脑的python路径
        pycommand command = new pycommand(PythonConfig.pythonBinPathConfig("D:\\python3.6\\python.exe"));
        //4. 执行,每次执行会生成临时文件 如C:\Users\ADMINI~1\AppData\Local\Temp\1623292234356-0\exec.py,这个带的日志输出能看到,搞定
        command.execute(Joiner.on('\n').join(scriptLines));

在这里插入图片描述

搞定。

Matplotlib 3D散点动画

Matplotlib 3D散点动画

我正在绘制星团中的位置,我的数据在具有x,y,z位置以及时间索引的数据框中。

我能够生成3d散点图,并试图生成旋转图-我虽然取得了一些成功,但是却在动画API方面苦苦挣扎。

如果我的“
update_graph”函数仅返回一个新的ax.scatter(),则除非我重建整个图,否则旧图将保持绘制状态。看来效率低下。同样,我必须将间隔设置得很高,否则我的动画每隔一帧就会“跳过”,所以这表示我的表现很差。最后,由于无法获得3D散点图的迭代器,我被迫使用“
blit = False”。显然“ graph.set_data()”不起作用,我可以使用“
graph.set_3d_properties”,但这只允许我使用新的z坐标。

所以我将一个簇集在一起-(我使用的数据在 https://www.kaggle.com/mariopasquato/star-cluster-
simulations
滚动到底部)

我也只画了100个点(data = data [data.id <100])

我的(工作)代码如下:

def update_graph(num):     ax = p3.Axes3D(fig)     ax.set_xlim3d([-5.0, 5.0])     ax.set_xlabel(''X'')     ax.set_ylim3d([-5.0, 5.0])     ax.set_ylabel(''Y'')     ax.set_zlim3d([-5.0, 5.0])     ax.set_zlabel(''Z'')     title=''3D Test, Time=''+str(num*100)     ax.set_title(title)     sample=data0[data0[''time'']==num*100]     x=sample.x     y=sample.y     z=sample.z     graph=ax.scatter(x,y,z)     return(graph)fig = plt.figure()ax = p3.Axes3D(fig)# Setting the axes propertiesax.set_xlim3d([-5.0, 5.0])ax.set_xlabel(''X'')ax.set_ylim3d([-5.0, 5.0])ax.set_ylabel(''Y'')ax.set_zlim3d([-5.0, 5.0])ax.set_zlabel(''Z'')ax.set_title(''3D Test'')data=data0[data0[''time'']==0]x=data.xy=data.yz=data.zgraph=ax.scatter(x,y,z)# Creating the Animation objectline_ani = animation.FuncAnimation(fig, update_graph, 19,                                interval=350, blit=False)plt.show()

答案1

小编典典

3D中的 散点图
是一个mpl_toolkits.mplot3d.art3d.Path3DCollection对象。这提供了一个_offsets3d托管元组的属性,(x,y,z)可用于更新散点的坐标。因此,不对动画的每次迭代都创建整个图,而仅更新其点可能是有益的。

以下是有关如何执行此操作的示例。

import numpy as npfrom matplotlib import pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport matplotlib.animationimport pandas as pda = np.random.rand(2000, 3)*10t = np.array([np.ones(100)*i for i in range(20)]).flatten()df = pd.DataFrame({"time": t ,"x" : a[:,0], "y" : a[:,1], "z" : a[:,2]})def update_graph(num):    data=df[df[''time'']==num]    graph._offsets3d = (data.x, data.y, data.z)    title.set_text(''3D Test, time={}''.format(num))fig = plt.figure()ax = fig.add_subplot(111, projection=''3d'')title = ax.set_title(''3D Test'')data=df[df[''time'']==0]graph = ax.scatter(data.x, data.y, data.z)ani = matplotlib.animation.FuncAnimation(fig, update_graph, 19,                                interval=40, blit=False)plt.show()

该解决方案不允许产生斑点。但是,根据使用情况,可能根本不需要使用散点图。使用 法线plot可能同样有可能,这会产生斑点-如以下示例所示。

import numpy as npfrom matplotlib import pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport matplotlib.animationimport pandas as pda = np.random.rand(2000, 3)*10t = np.array([np.ones(100)*i for i in range(20)]).flatten()df = pd.DataFrame({"time": t ,"x" : a[:,0], "y" : a[:,1], "z" : a[:,2]})def update_graph(num):    data=df[df[''time'']==num]    graph.set_data (data.x, data.y)    graph.set_3d_properties(data.z)    title.set_text(''3D Test, time={}''.format(num))    return title, graph,fig = plt.figure()ax = fig.add_subplot(111, projection=''3d'')title = ax.set_title(''3D Test'')data=df[df[''time'']==0]graph, = ax.plot(data.x, data.y, data.z, line, marker="o")ani = matplotlib.animation.FuncAnimation(fig, update_graph, 19,                                interval=40, blit=True)plt.show()

Matplotlib Toolkits:三维绘图工具包 matplotlib.mplot3d

Matplotlib Toolkits:三维绘图工具包 matplotlib.mplot3d

http://blog.csdn.net/pipisorry/article/details/40008005

Matplotlib mplot3d 工具包简介

The mplot3d toolkit adds simple 3D plotting capabilities to matplotlib by supplying an axes object that can create a 2D projection of a 3D scene. The resulting graph will have the same look and feel as regular 2D plots.

创建 Axes3D 对象

An Axes3D object is created just like any other axes using the projection=‘3d’ keyword. Create a new matplotlib.figure.Figure and add a new axes to it of type Axes3D:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection=’3d’)
New in version 1.0.0: This approach is the preferred method of creating a 3D axes.
Note: Prior to version 1.0.0, the method of creating a 3D axes was di erent. For those using older versions of matplotlib, change ax = fig.add_subplot(111, projection=’3d’) to ax = Axes3D(fig).

要注意的地方

Axes3D 展示三维图形时,其初始视图中 x,y 轴与我们一般看的视图(自己画的时候的视图)是反转的,matlab 也是一样。

可以通过设置初始视图来改变角度:ax.view_init (30, 35)

Note: 不过这样图形可能会因为旋转而有阴影,也可以通过代码中 XY 轴互换来实现视图中 XY 互换。不知道有没有其它方法,如 matlab 中就有 surf (x,y,z);set (gca,''xdir'',''reverse'',''ydir'',''reverse'') 这样命令来实现这个功能 [关于 matlab 三维图坐标轴原点位置的问题]。

lz 总结绘制三维图形一般流程

创建 Axes3D 对象

fig = plt.figure()
ax = Axes3D(fig)
再进行坐标范围设定什么的(可选)

# 计算坐标极限值
xs = list(itertools.chain.from_iterable([xi[0] for xi in x]))
x_max, x_min = max(xs), min(xs)
ys = list(itertools.chain.from_iterable([xi[1] for xi in x]))
y_max, y_min = max(ys), min(ys)
zs = list(itertools.chain.from_iterable([xi[2] for xi in x]))
z_max, z_min = max(zs), min(zs)
margin = 0.1

再进行绘制,如

plt.scatter(x_new[0], x_new[1], c=''r'', marker=''*'', s=50, label=''new x'')
ax.scatter(xs, ys, zs, c=c, marker=marker, s=50, label=label)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, label=''Discrimination Interface'')
再进行一些坐标什么的设置

# 设置图形展示效果
ax.set_xlim(x_min - margin, x_max + margin)
ax.set_ylim(y_min - margin, y_max + margin)
ax.set_zlim(z_min - margin, z_max + margin)
ax.set_xlabel(''x'')
ax.set_ylabel(''y'')
ax.set_zlabel(''z'')
ax.legend(loc=''lower right'')
ax.set_title(''Plot of class0 vs. class1'')
ax.view_init(30, 35)
最后显示出来

plt.show()

皮皮 blog



绘制不同三维图形

Line plots 线图


Scatter plots 散点图

Axes3D.scatter(xs, ys, zs=0, zdir=u''z'', s=20, c=u''b'', depthshade=True, *args, **kwargs)

Create a scatter plot

Argument Description
xs, ys Positions of data points.
zs Either an array of the same length as xs andys or a single value to place all points inthe same plane. Default is 0.
zdir Which direction to use as z (‘x’, ‘y’ or ‘z’)when plotting a 2D set.
s size in points^2. It is a scalar or an array of thesame length as x andy.
c a color. c can be a single color format string, or asequence of color specifications of lengthN, or asequence ofN numbers to be mapped to colors using thecmap andnorm specified via kwargs (see below). Notethatc should not be a single numeric RGB or RGBAsequence because that is indistinguishable from an arrayof values to be colormapped.c can be a 2-D array inwhich the rows are RGB or RGBA, however.
depthshade Whether or not to shade the scatter markers to givethe appearance of depth. Default isTrue.
Keyword arguments are passed on to scatter().
Returns a Patch3DCollection
Note: scatter ( x, y, s=20, c=u''b'', marker=u''o'', cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, **kwargs )
../../_images/scatter3d_demo1.png


Wireframe plots 线框图


Surface plots 曲面图

参数

x, y, z: x,y,z 轴对应的数据。注意 z 的数据的 z.shape 是 (len (y), len (x)),不然会报错:ValueError: shape mismatch: objects cannot be broadcast to a single shape

rstride    Array row stride (step size), defaults to 10
cstride    Array column stride (step size), defaults to 10

示例 1:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)
ax.contourf(X, Y, Z, zdir=''z'', offset=-2, cmap=plt.cm.hot)
ax.set_zlim(-2,2)

# savefig(''../figures/plot3d_ex.png'',dpi=48)
plt.show()
结果图形输出:

示例 2:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)

x = np.arange(0, 200)
y = np.arange(0, 100)
x, y = np.meshgrid(x, y)
z = np.random.randint(0, 200, size=(100, 200))%3
print(z.shape)

# ax.scatter(x, y, z, c=''r'', marker=''.'', s=50, label='''')
ax.plot_surface(x, y, z,label='''')
plt.show()

[surface-plots]

[Matplotlib tutorial - 3D Plots]


Tri-Surface plots 三面图


Contour plots 等高线图


Filled contour plots 填充等高线图


Polygon plots 多边形图

Axes3D.add_collection3d(col, zs=0, zdir=u''z'')

Add a 3D collection object to the plot.

2D collection types are converted to a 3D version bymodifying the object and adding z coordinate information.

Supported are:

  • PolyCollection
  • LineColleciton
  • PatchCollection
绘图原理是:设置好多面体(如正文体)的顶点坐标和所有面对应的顶点,加上一些属性(如颜色、宽度、透明度)

绘制正方体和四面体示例

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''''
__author__ = ''皮''
__mtime__ = ''9/27/2015-027''
__email__ = ''pipisorry@126.com''
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

fig = plt.figure()
ax = fig.gca(projection=''3d'')


# 正文体顶点和面
verts = [(0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1), (1, 0, 1)]
faces = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [0, 3, 7, 4]]
# 四面体顶点和面
# verts = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (1, 0, 1)]
# faces = [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]
# 获得每个面的顶点
poly3d = [[verts[vert_id] for vert_id in face] for face in faces]
# print(poly3d)

# 绘制顶点
x, y, z = zip(*verts)
ax.scatter(x, y, z)
# 绘制多边形面
ax.add_collection3d(Poly3DCollection(poly3d, facecolors=''w'', linewidths=1, alpha=0.3))
# ax.add_collection3d(Line3DCollection(poly3d, colors=''k'', linewidths=0.5, linestyles='':''))

 # 设置图形坐标范围ax.set_xlabel(''X'')ax.set_xlim3d(-0.5, 1.5)ax.set_ylabel(''Y'')ax.set_ylim3d(-0.5, 1.5)ax.set_zlabel(''Z'')ax.set_zlim3d(-0.5, 1.5)plt.show()

绘制结果截图

  

[Transparency for Poly3DCollection plot in matplotlib]


Bar plots 条形图


2D plots in 3D 三维图中的二维图


Text 文本图


Subplotting 子图

皮皮 blog



matplotlib.mplot3d 绘图实例

matplotlib 绘制 2 维高斯分布

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
rv = stats.multivariate_normal([0, 0], cov=1)

x, y = np.mgrid[-3:3:.15, -3:3:.15]
ax.plot_surface(x, y, rv.pdf(np.dstack((x, y))), rstride=1, cstride=1)
ax.set_zlim(0, 0.2)

# savefig(''../figures/plot3d_ex.png'',dpi=48)
plt.show()


matplotlib 绘制平行 z 轴的平面

(垂直 xy 平面的平面)

方程:0*Z + A [0] X + A [1] Y + A [-1] = 0

X = np.arange(x_min - margin, x_max + margin, 0.05)
Z = np.arange(z_min - margin, z_max + margin, 0.05)
X, Z = np.meshgrid(X, Z)
Y = -1 / A[1] * (A[0] * X + A[-1])
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, label=''Discrimination Interface'')

from:http://blog.csdn.net/pipisorry/article/details/40008005

ref:mplot3d tutorial(inside source code)

mplot3d API

[mplot3d¶]


今天关于使用matplotlib的3D动画matplotlib 3d动画的介绍到此结束,谢谢您的阅读,有关ImportError:未安装带有matplotlib的名为matplotlib的模块、java版matplotlib,matplotlib4j使用,java中调用matplotlib或者其他python脚本、Matplotlib 3D散点动画、Matplotlib Toolkits:三维绘图工具包 matplotlib.mplot3d等更多相关知识的信息可以在本站进行查询。

本文标签: