[英]Drawing hatch filled rectangles with differing angles in python
我正试图在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()
生成如下所示的图形。 但在检查时,角度与输入角度不匹配。
我有一个基本的想法,虽然我怀疑你需要做更多的工作,这取决于你想要结果的灵活性。
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
并使用旋转矩阵旋转它来获得xprime
和yprime
,它们是与x轴成一定角度的线的坐标,偏移量为c
。 迭代几个c
值覆盖单位平方,通过使offset
参数更小,可以使线更密集。
其次,我们需要一种方法来绘制彼此相邻的轴。 我已经使用了subplots
。 这将返回fig, axes
的axes
是轴实例的数组,所以我们通过它们iteratate它们传递到函数绘制舱口和每次给它一个随机角度。
编辑我已经改变了plot_hatches代码以逆时针方式旋转(在此编辑之前是顺时针方向)。 现在,这将生成具有数组[0, -45, 0, 45, 0]
的问题中给出的图像:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.