在 Matplotlib 的 Polar/Radial 条形图中获取条形图顶部的标签,Python3

Getting Labels on top of Bar in Polar/Radial Bar Chart in Matplotlib, Python3

我想创建一个径向条形图。我有以下 Python3 代码:

lObjectsALLcnts = [1, 1, 1, 2, 2, 3, 5, 14, 15, 20, 32, 33, 51, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 6, 7, 7, 10, 10, 14, 14, 14, 17, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 5, 5, 6, 14, 14, 27, 27, 1, 1, 2, 3, 4, 4, 5]`

lObjectsALLlbls = ['DuctPipe', 'Column', 'Protrusion', 'Tree', 'Pole', 'Bar', 'Undefined', 'EarthingConductor', 'Grooves', 'UtilityPipe', 'Cables', 'RainPipe', 'Moulding', 'Intrusion', 'PowerPlug', 'UtilityBox', 'Balcony', 'Lighting', 'Lock', 'Doorbell', 'Alarm', 'LetterBox', 'Grate', 'Undefined', 'CableBox', 'Canopy', 'Vent', 'PowerBox', 'UtilityHole', 'Recess', 'Protrusion', 'Shutter', 'Handrail', 'Lock', 'Mirror', 'SecuritySpike', 'Bench', 'Intrusion', 'Picture', 'Showcase', 'Camera', 'Undefined', 'Stair', 'Protrusion', 'Alarm', 'Graffiti', 'Lighting', 'Ornaments', 'SecurityBar', 'Grate', 'Vent', 'Lighting', 'UtilityHole', 'Intrusion', 'Undefined', 'Protrusion']

iN = len(lObjectsALLcnts)
arrCnts = np.array(lObjectsALLcnts)

theta=np.arange(0,2*np.pi,2*np.pi/iN)
width = (2*np.pi)/iN *0.9

fig = plt.figure(figsize=(8, 8))
ax = fig.add_axes([0.1, 0.1, 0.75, 0.75], polar=True)
bars = ax.bar(theta, arrCnts, width=width, bottom=50)
ax.set_xticks(theta)
plt.axis('off')

创建以下图像:

radialbartchart_nolabels

创建这个之后我想添加标签,但是我在找到正确的坐标时遇到了一些麻烦。标签应沿条形的方向旋转。

我想出的最好办法是添加以下代码:

rotations = [np.degrees(i) for i in theta]
for i in rotations: i = int(i)
for x, bar, rotation, label in zip(theta, bars, rotations, lObjectsALLlbls):
     height = bar.get_height() + 50
     ax.text(x + bar.get_width()/2, height, label, ha='center', va='bottom', rotation=rotation)

创建以下内容:

radialbarchart_wlabels

有人能帮我找到标签的正确坐标吗?我一直在寻找 Adding value labels on a matplotlib bar chart 之类的答案 并将其转换为极坐标条形图。但是没有成功。

提前致谢,

在 Whosebug 上 reader 很久了,但第一次找不到答案。

您 运行 遇到的问题是文本边界框被扩展以承载完整的旋转文本,但该框本身仍然在笛卡尔坐标中定义。下图显示了水平对齐 "left" 和垂直对齐 "bottom" 的两个文本;问题是旋转的文本的边界框边缘离文本更远。

您想要的是让文本围绕其自身周围的边缘点旋转,如下所示。

这可以使用 matplotlib.text.Textrotation_mode="anchor" 参数来实现,它完全控制了上述功能。

ax.text(..., rotation_mode="anchor")

在这个例子中:

from matplotlib import pyplot as plt
import numpy as np

lObjectsALLcnts = [1, 1, 1, 2, 2, 3, 5, 14, 15, 20, 32, 33, 51, 1, 1, 2, 2, 3, 3, 3, 3, 
                   3, 4, 6, 7, 7, 10, 10, 14, 14, 14, 17, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 
                   5, 5, 6, 14, 14, 27, 27, 1, 1, 2, 3, 4, 4, 5]

lObjectsALLlbls = ['DuctPipe', 'Column', 'Protrusion', 'Tree', 'Pole', 'Bar', 'Undefined', 
                   'EarthingConductor', 'Grooves', 'UtilityPipe', 'Cables', 'RainPipe', 'Moulding', 
                   'Intrusion', 'PowerPlug', 'UtilityBox', 'Balcony', 'Lighting', 'Lock', 'Doorbell', 
                   'Alarm', 'LetterBox', 'Grate', 'Undefined', 'CableBox', 'Canopy', 'Vent', 'PowerBox', 
                   'UtilityHole', 'Recess', 'Protrusion', 'Shutter', 'Handrail', 'Lock', 'Mirror', 
                   'SecuritySpike', 'Bench', 'Intrusion', 'Picture', 'Showcase', 'Camera', 
                   'Undefined', 'Stair', 'Protrusion', 'Alarm', 'Graffiti', 'Lighting', 'Ornaments', 
                   'SecurityBar', 
                   'Grate', 'Vent', 'Lighting', 'UtilityHole', 'Intrusion', 'Undefined', 'Protrusion']

iN = len(lObjectsALLcnts)
arrCnts = np.array(lObjectsALLcnts)

theta=np.arange(0,2*np.pi,2*np.pi/iN)
width = (2*np.pi)/iN *0.9
bottom = 50

fig = plt.figure(figsize=(8,8))
ax = fig.add_axes([0.1, 0.1, 0.75, 0.75], polar=True)
bars = ax.bar(theta, arrCnts, width=width, bottom=bottom)

plt.axis('off')

rotations = np.rad2deg(theta)
for x, bar, rotation, label in zip(theta, bars, rotations, lObjectsALLlbls):
    lab = ax.text(x,bottom+bar.get_height() , label, 
             ha='left', va='center', rotation=rotation, rotation_mode="anchor",)   
plt.show()

请注意,这使用给定的 50 个底部间距单位。您可以稍微增加此数字以增加条形和文本之间的间距。


此答案的以下初始版本不知何故已过时。我会留在这里供参考。

您 运行 遇到的问题是文本边界框被扩展以承载完整的旋转文本,但该框本身仍然在笛卡尔坐标中定义。下图显示了水平对齐 "left" 和垂直对齐 "bottom" 的两个文本;问题是旋转的文本的边界框边缘离文本更远。

一个简单的解决方案可能是将水平和垂直对齐方式定义为 "center",这样文本的轴心保持不变,与其旋转无关。

接下来的问题就是对文本中心和条形图顶部之间的距离进行良好的估计。

可以将文本中字母数的一半乘以某个因数。这需要通过反复试验才能找到。

bottom = 50
rotations = np.rad2deg(theta)
y0,y1 = ax.get_ylim()

for x, bar, rotation, label in zip(theta, bars, rotations, lObjectsALLlbls):
     offset = (bottom+bar.get_height())/(y1-y0)
     h =offset + len(label)/2.*0.032
     lab = ax.text(x, h, label, transform=ax.get_xaxis_transform(), 
             ha='center', va='center')
     lab.set_rotation(rotation)

您也可以尝试找出渲染文本的实际大小,并使用此信息找出坐标,

bottom = 50
rotations = np.rad2deg(theta)
y0,y1 = ax.get_ylim()

for x, bar, rotation, label in zip(theta, bars, rotations, lObjectsALLlbls):
     offset = (bottom+bar.get_height())/(y1-y0)
     lab = ax.text(0, 0, label, transform=None, 
             ha='center', va='center')
     renderer = ax.figure.canvas.get_renderer()
     bbox = lab.get_window_extent(renderer=renderer)
     invb = ax.transData.inverted().transform([[0,0],[bbox.width,0] ])
     lab.set_position((x,offset+(invb[1][0]-invb[0][0])/2.*2.7 ) )
     lab.set_transform(ax.get_xaxis_transform())
     lab.set_rotation(rotation)

复制的完整代码:

import numpy as np
import matplotlib.pyplot as plt

lObjectsALLcnts = [1, 1, 1, 2, 2, 3, 5, 14, 15, 20, 32, 33, 51, 1, 1, 2, 2, 3, 3, 3, 3, 
               3, 4, 6, 7, 7, 10, 10, 14, 14, 14, 17, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 
               5, 5, 6, 14, 14, 27, 27, 1, 1, 2, 3, 4, 4, 5]

lObjectsALLlbls = ['DuctPipe', 'Column', 'Protrusion', 'Tree', 'Pole', 'Bar', 'Undefined', 
               'EarthingConductor', 'Grooves', 'UtilityPipe', 'Cables', 'RainPipe', 'Moulding', 
               'Intrusion', 'PowerPlug', 'UtilityBox', 'Balcony', 'Lighting', 'Lock', 'Doorbell', 
               'Alarm', 'LetterBox', 'Grate', 'Undefined', 'CableBox', 'Canopy', 'Vent', 'PowerBox', 
               'UtilityHole', 'Recess', 'Protrusion', 'Shutter', 'Handrail', 'Lock', 'Mirror', 
               'SecuritySpike', 'Bench', 'Intrusion', 'Picture', 'Showcase', 'Camera', 
               'Undefined', 'Stair', 'Protrusion', 'Alarm', 'Graffiti', 'Lighting', 'Ornaments', 
               'SecurityBar', 
               'Grate', 'Vent', 'Lighting', 'UtilityHole', 'Intrusion', 'Undefined', 'Protrusion']

iN = len(lObjectsALLcnts)
arrCnts = np.array(lObjectsALLcnts)

theta=np.arange(0,2*np.pi,2*np.pi/iN)
width = (2*np.pi)/iN *0.9
bottom = 50

fig = plt.figure(figsize=(8,8))
ax = fig.add_axes([0.1, 0.1, 0.75, 0.75], polar=True)
bars = ax.bar(theta, arrCnts, width=width, bottom=bottom)

plt.axis('off')

rotations = np.rad2deg(theta)
y0,y1 = ax.get_ylim()

for x, bar, rotation, label in zip(theta, bars, rotations, lObjectsALLlbls):
 offset = (bottom+bar.get_height())/(y1-y0)
 lab = ax.text(0, 0, label, transform=None, 
         ha='center', va='center')
 renderer = ax.figure.canvas.get_renderer()
 bbox = lab.get_window_extent(renderer=renderer)
 invb = ax.transData.inverted().transform([[0,0],[bbox.width,0] ])
 lab.set_position((x,offset+(invb[1][0]-invb[0][0])/2.*2.7 ) )
 lab.set_transform(ax.get_xaxis_transform())
 lab.set_rotation(rotation)

 
plt.show()

不幸的是,又涉及到一些奇怪的因素2.7。更不幸的是,在这种情况下,我完全不知道为什么它必须在那里。但结果可能仍然足够好。

也可以使用这个问题的解决方案: