如果在Matplotlib中设置线宽,则必须以磅为单位给出线宽。在我的情况下,我有两个圆圈,都是半径R,我想用一条线连接它们。我希望这条线宽2 * R,以获得棒状。但是,当我说myLines[i].set_linewidth(2*R)
时,无论我放大了多少,这都会使线条始终具有特定的厚度。
有没有办法让线条的特定厚度不是基于像素或点的数量,而是用轴缩放?如何让我的线条与我的圆圈直径相同?
我希望我能够很好地解释自己,我期待着回答。
答案 0 :(得分:1)
正如您已经想到的那样,线宽是在轴空间中指定的,而不是数据空间。要在数据空间中绘制线条,请改为绘制矩形:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Circle
r = 5 # rod radius
x1, y1 = (0,0) # left end of rod
x2, y2 = (10,0) # right end of rod
# create 2 circles and a joining rectangle
c1 = Circle((x1, y1), r, color='r')
c2 = Circle((x2, y2), r)
rect = Rectangle((x1, y1-r), width=x2-x1, height=2*r)
# plot artists
fig, ax = plt.subplots(1,1)
for artist in [c2, rect, c1]:
ax.add_artist(artist)
# need to set axis limits manually
ax.set_xlim(x1-r-1, x2+r+1)
ax.set_ylim(y1-r-1, y2+r+1)
# set aspect so circle don't become oval
ax.set_aspect('equal')
plt.show()
答案 1 :(得分:1)
为了以数据单位绘制线宽,您可能需要查看 this answer 。
它使用类data_linewidth_plot
,它与plt.plot()
命令的签名非常相似。
l = data_linewidth_plot( x, y, ax=ax, label='some line', linewidth = 1, alpha = 0.4)
linewidth参数以(y-)数据单位解释。
使用此解决方案甚至不需要绘制圆圈,因为可以简单地使用solid_capstyle="round"
参数。
R=0.5
l = data_linewidth_plot( [0,3], [0.7,1.4], ax=ax, solid_capstyle="round",
linewidth = 2*R, alpha = 0.4)