如果您对PolarMatplotlib图中的箭头和matplotlib画箭头感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解PolarMatplotlib图中的箭头的各种细节,并对matplot
如果您对Polar Matplotlib图中的箭头和matplotlib 画箭头感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解Polar Matplotlib图中的箭头的各种细节,并对matplotlib 画箭头进行深入的分析,此外还有关于java版matplotlib,matplotlib4j使用,java中调用matplotlib或者其他python脚本、Matplotlib Polar散点图未显示所有点、Matplotlib Toolkits:三维绘图工具包 matplotlib.mplot3d、Matplotlib中的动画箭头的实用技巧。
本文目录一览:- Polar Matplotlib图中的箭头(matplotlib 画箭头)
- java版matplotlib,matplotlib4j使用,java中调用matplotlib或者其他python脚本
- Matplotlib Polar散点图未显示所有点
- Matplotlib Toolkits:三维绘图工具包 matplotlib.mplot3d
- Matplotlib中的动画箭头
Polar Matplotlib图中的箭头(matplotlib 画箭头)
我正在尝试绘制串联RLC电路中电阻,电容器和电感器两端电压的相量。我已经完成了所有的计算,我可以得到仅正常的体面图ax.plot(theta,r,....)
。
我想使相量矢量看起来像箭头。我一直在尝试使用,ax.arrow(0,0,theta,magnitude)
但看起来仍然像是一条线。我编写的代码的要点在这里:GIST
我创建的图像是
我尝试遵循在此列表中找到的示例,因为它与我要完成的操作非常相似,它产生以下图像:
当我在计算机上运行他们的代码时,我得到
我在Xubuntu 14.04上并运行matplotlib 1.3.1。我确实看到我正在使用的示例在2009年使用matplotlib 0.99。
任何帮助将非常感激。
答案1
小编典典箭头大小太大,这是:
import matplotlibimport numpy as npimport matplotlib.pyplot as pltprint "matplotlib.__version__ = ", matplotlib.__version__print "matplotlib.get_backend() = ", matplotlib.get_backend()# radar green, solid grid linesplt.rc(''grid'', color=''#316931'', linewidth=1, line-'')plt.rc(''xtick'', labelsize=15)plt.rc(''ytick'', labelsize=15)# force square figure and square axes looks better for polar, IMOwidth, height = matplotlib.rcParams[''figure.figsize'']size = min(width, height)# make a square figurefig = plt.figure(figsize=(size, size))ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg=''#d5de9c'')r = np.arange(0, 3.0, 0.01)theta = 2*np.pi*rax.plot(theta, r, color=''#ee8d18'', lw=3)ax.set_rmax(2.0)plt.grid(True)ax.set_title("And there was much rejoicing!", fontsize=20)#This is the line I added:arr1 = plt.arrow(0, 0.5, 0, 1, alpha = 0.5, width = 0.015, edgecolor = ''black'', facecolor = ''green'', lw = 2, zorder = 5)# arrow at 45 degreearr2 = plt.arrow(45/180.*np.pi, 0.5, 0, 1, alpha = 0.5, width = 0.015, edgecolor = ''black'', facecolor = ''green'', lw = 2, zorder = 5)plt.show()
产生:
更好?:)
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);
所以想要更全面的用法还得自己动手,几种办法:
- 大部分还是用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);
- 这种比较直接,参照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 Polar散点图未显示所有点
这是我的建议,如果我正确理解您的问题,则此代码会自动绘制所有要点
这里我只是使用for循环遍历所有点
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111,polar = True)
a = [1,1.5,2]
for idx,i in enumerate([-1.3,.4,-.2]):
c = ax.scatter([i],[a[idx]])
plt.show()
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. - 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 )

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中的动画箭头
答案
您可以使用ax.arrow
绘制箭头。
请注意,您应该在每次迭代时使用ax.cla()
清除图形,并使用ax.set()
调整轴限制。
代码
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig,ax = plt.subplots(figsize=(12,8))
ax.set(xlim=(0,104),ylim=(0,68))
x_start,y_start = (50,35)
x_end,y_end = (90,45)
N = 50
x = np.linspace(x_start,x_end,N)
y = np.linspace(y_start,y_end,N)
def animate(i):
ax.cla()
ax.arrow(x_start,y_start,x[i] - x_start,y[i] - y_start,head_width = 2,head_length = 2,fc = 'black',ec = 'black')
ax.set(xlim = (0,ylim = (0,68))
ani = animation.FuncAnimation(fig,animate,interval=20,frames=N,blit=False,save_count=50)
plt.show()
动画
也许看看here
您可以简单地将line功能更改为arrow功能。
但请注意,您首先需要计算箭头的终点,因为根据文档,您只能指定长度dx,dy。通过使用毕达哥拉斯,起点将是x[0]
,y[0]
和dx
,dy
是翻译后的端点。
我认为您现在可以自行解决。
关于Polar Matplotlib图中的箭头和matplotlib 画箭头的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于java版matplotlib,matplotlib4j使用,java中调用matplotlib或者其他python脚本、Matplotlib Polar散点图未显示所有点、Matplotlib Toolkits:三维绘图工具包 matplotlib.mplot3d、Matplotlib中的动画箭头等相关知识的信息别忘了在本站进行查找喔。
本文标签: