极坐标图中的误差条不随角度旋转
我想用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()
我该怎么做才能让误差条考虑到每个柱子的角度呢?
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)