我正在尝试在python中绘制一个2D矩形板。该板将被分成可变数量的部分,这些部分中的每一个将用阴影图案填充。该阴影图案将具有指定的角度。作为具有5个截面的矩形的示例,其截面的数组阴影取向(以度为单位)为[0,45,0,-45,0],如下所示。它需要能够显示任何方向,而不仅仅是通常的90,45,0,即33,74.5等。
知道我怎么能这样做吗?基本上我只想在每个部分中显示方向,任何其他表达相同结果的方法都将非常受欢迎,例如:一条线而不是阴影线。
编辑(问题解答后): Greg提供的编辑脚本如下所示。
from numpy import cos, sin
import numpy as np
import matplotlib.pyplot as plt
angles = [0,10,20,30,40,50]
numberOfSections = len(angles)
def plot_hatches(ax, angle, offset=.1):
angle_radians = np.radians(angle)
x = np.linspace(-1, 1, 10)
for c in np.arange(-2, 2, offset):
yprime = cos(angle_radians) * c - sin(angle_radians) * x
xprime = sin(angle_radians) * c + cos(angle_radians) * x
ax.plot(xprime, yprime, color="b", linewidth=2)
ax.set_ylim(0, 1)
ax.set_xlim(0, 1)
return ax
fig, axes = plt.subplots(nrows=1, ncols=numberOfSections, figsize=(16,(16/numberOfSections)), sharex=True, sharey=True)
for i in range(len(axes.flat)):
plot_hatches(axes.flat[i], angles[i])
fig.subplots_adjust(hspace=0, wspace=0)
plt.show()
生成如下所示的图形。
但在检查时,角度与输入角度不匹配。
答案 0 :(得分:3)
我有一个基本的想法,虽然我怀疑你需要做更多的工作,这取决于你想要的结果有多灵活。
from numpy import cos, sin
import numpy as np
import matplotlib.pyplot as plt
def plot_hatches(ax, angle, offset=.1):
angle_radians = np.radians(angle)
x = np.linspace(-2, 2, 10)
for c in np.arange(-2, 2, offset):
yprime = cos(angle_radians) * c + sin(angle_radians) * x
xprime = sin(angle_radians) * c - cos(angle_radians) * x
ax.plot(xprime, yprime, color="k")
ax.set_ylim(0, 1)
ax.set_xlim(0, 1)
return ax
fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(8,8), sharex=True, sharey=True)
for i in range(len(axes.flat)):
plot_hatches(axes.flat[i], np.random.uniform(0, 90))
fig.subplots_adjust(hspace=0, wspace=0)
这里有两个部分:首先是一个函数plot_hatches
,它在轴ax
上的单位正方形上绘制阴影。这是通过使用单行x, y=c
并使用rotation matrix旋转它来获得xprime
和yprime
来完成的,这些线是与x轴成一定角度的线的坐标。偏移c
。迭代几个c
的值覆盖单位正方形,通过使offset
参数更小,可以使线更密集。
其次,我们需要一种方法来绘制彼此相邻的轴。我使用subplots
完成了这项工作。这返回fig, axes
axes
是一个轴实例数组,因此我们通过它们进行迭代,将它们传递给函数以绘制阴影并每次给它一个随机角度。
修改强>
我已经将plot_hatches代码更改为以逆时针方式旋转(在此编辑之前是顺时针方向)。现在,这将生成具有数组[0, -45, 0, 45, 0]
的问题中给出的图像: