首页 文章

极坐标绘图误差条不会在matplotlib中以角度旋转

提问于
浏览
2

我想在matplotlib中创建一个带有误差条的极点条形图 . 当我使用下面的代码时,我的所有误差条都有一个水平对齐,看起来不对,除非条形对应于90度或270度的情况 .

from numpy import *
from matplotlib import pyplot as py


r=zeros([16])
err=zeros([16]) 
for i in range(16):
    r[i]=random.randint(400,600)
    err[i]=random.randint(20,50)
theta=arange(0,2*pi,2*pi/16)
width = pi*2/16

fig = py.figure(figsize=(8,8))
ax = fig.add_axes([0.1, 0.1, 0.75, 0.79], polar=True)

bars = ax.bar(theta+pi/16, r, width=width, bottom=0.0,yerr=err)
ax.set_ylim(0,700)
py.show()

the figure

如何获取误差线以考虑单个条的theta?

1 回答

  • 2

    因此,似乎错误条是使用Line2D对象创建的;也就是说,绘制虚线,其中数据点对应于误差条位置(x [i],y [i] yerr [i]) . 行中的破折号始终相同,因为它们只是符号 . 这显然不适用于极地情节 . 因此,需要删除此错误栏设置,并且必须单独添加每个错误栏,并使用正确方向的行 .

    这是一个执行此操作的例程:

    from matplotlib.lines import Line2D
    from math import acos,sqrt
    
    def correct_errorbar(ax,barlen=50,errorline=1):
        """
        A routine to remove default y-error bars on a bar-based pie chart and 
        replace them  with custom error bars that rotate with the pie chart.
        ax -- the axes object that contains the polar coordinate bar chart
        barlen -- the perpendicular length of each error bar
        errorline -- the number of the Line2D object that represents the original
           horizontal error bars.
    
        barlen will depend on the magnitude of the "y" values, ie the radius. 
        This routine was tested with a plot consisting solely of bar chart, and 
        if other Line2D objects are added, either directly or through further
        plot commands, errorline many need to be adjusted from its default value. 
        """
        # get error bar positions
        x,y = ax.lines[errorline].get_data()
        # remove incorrect bars
        del ax.lines[errorline]
        # add new lines fixing bars
        for i in range(len(y)):
            r = sqrt(barlen*barlen/4+y[i]*y[i])
            dt = acos((y[i])/(r))
            newline = Line2D([x[i]-dt,x[i]+dt],[r,r],lw=barlen/100.)
            ax.add_line(newline)
    

相关问题