如何将标签与极坐标条形图的内边缘对齐

时间:2017-01-12 17:16:56

标签: python matplotlib

我很难做出我想要的可视化效果。我还不能放图像所以链接在下面。我几乎拥有我想要的东西。问题是标签放置不正确。

反转极性-BAR-演示

NSUndoManager: capturing reference types possible?

我想让标签像它们一样旋转,但是有标签'右边缘恰好在圆圈的外边缘内部对齐。

编辑澄清:
我在这个例子中使用的标签都是测试'。对于实际数据,这些标签将具有不同的长度。我希望移动标签的末尾,以便它们的最后一个字母位于圆圈的外边缘旁边。因此,在这种情况下,所有的' g将位于外边缘旁边。

import matplotlib.pyplot as mpl
import numpy as np
import random

bgcolor = '#222222'
barcolor = '#6699cc'
bottom = 15

N = 32
Values = np.random.random(N)*10
MetricLabels = ['testing' for _ in range(1, N+1)]

# Select the radii, thetas, and widths.
Radii = -5*np.ones(N)-Values
Theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
width = 2*np.pi/N

# Make a list of shifted thetas to place the labels at.
ThetaShifted = np.copy(Theta)
for i in range(N-1):
    ThetaShifted[i] = (Theta[i] + Theta[i+1])/2.0
ThetaShifted[-1] = (Theta[-1] + 2.0*np.pi)/2.0

# Make the figure
fig = mpl.figure()
ax = fig.add_subplot(111, projection='polar')
bars = ax.bar(Theta, Radii, width=width, bottom=bottom)

# Set the outer ring to be invisible.
ax.spines["polar"].set_visible(False)

# Set the grid line locations but set the labels to be invisible.
ax.grid(False)
ax.set_thetagrids([], visible=False)
ax.set_rgrids([3], visible=False)

# Apply colors to bars based on the settings above.
for v, bar in zip(Values, bars):
        bar.set_facecolor(barcolor)
        bar.set_edgecolor(bar.get_facecolor())

# Show the metric and value labels
for counter in range(N):
    ax.text(ThetaShifted[counter], bottom-3, MetricLabels[counter], 
            horizontalalignment='center', verticalalignment='baseline', 
            rotation=(counter+.5)*360/N, color=bgcolor)
    ax.text(ThetaShifted[counter], bottom+0.75, np.round(Values[counter],2), 
            horizontalalignment='center', verticalalignment='center', 
            color=bars[counter].get_facecolor())

# Set the background color to be a dark grey,
ax.set_axis_bgcolor(bgcolor)
fig.set_facecolor(bgcolor)

# Show the figure.
mpl.show()

2 个答案:

答案 0 :(得分:1)

如果我正确理解你想要的内容,你必须将rotation属性添加到counter周期的第二次调用中并将文本对齐如下:

...
# Show the metric and value labels
for counter in range(N):
    ax.text(ThetaShifted[counter], bottom-3, MetricLabels[counter], 
            horizontalalignment='center', verticalalignment='baseline', 
            rotation=(counter+.5)*360/N, color=bgcolor)
    ax.text(ThetaShifted[counter], bottom+2.5, np.round(Values[counter],2), 
            horizontalalignment='center', verticalalignment='center', 
            rotation=(counter+.5)*360/N, 
            color=bars[counter].get_facecolor())
 ...

enter image description here

答案 1 :(得分:1)

我实际上解决了我的问题。请参阅下面的图片和代码。解决这个问题的主要方法是使用等宽字体系列,并使用rjust创建标签字符串,从一开始就是固定长度和右对齐。在那之后,只需为每个标签选择正确的径向位置,当它们的字符数相同时应该更容易。

Initial demo solved

read