调整散点图的注释位置

时间:2019-05-28 11:13:02

标签: python matplotlib

我有一个散点图+注释:

enter image description here

我用以下代码注释了每个点:

for i, txt in enumerate(labels):
    ax.annotate(txt, (x[i], y[i]), 
            fontproperties=cur_font, 
            ha='center',
            va='top',
            fontsize=14)

从图中可以看到,文本与饼图重叠。我可以y[i] - 0.05来解决这个问题。但是我想知道是否有一种方法可以自动计算0.05部分,以使代码适合任何x&y输入。

绘制圆的代码:

draw_scatter_pie首先被调用,然后调用draw_pie以绘制每个饼图。

def draw_pie(
    dist: List[float], xpos: float, ypos: float, size: float, ax  # pie各个slice的大小占比
) -> None:

    # for incremental pie slices
    cumsum = np.cumsum(dist)
    cumsum = cumsum / cumsum[-1]
    pie = [0] + cumsum.tolist()

    counter = 0

    # draw each pie slices
    # for my data, there are only two slices for each pie chart
    for r1, r2 in zip(pie[:-1], pie[1:]):
        angles = np.linspace(2 * np.pi * r1, 2 * np.pi * r2)
        x = [0] + np.cos(angles).tolist()
        y = [0] + np.sin(angles).tolist()

        xy = np.column_stack([x, y])
        ax.scatter(
            xpos,
            ypos,
            marker=xy,
            s=size,
            facecolor=("indigo" if counter == 0 else "#CDCDCD"),
        )
        counter += 1


def draw_scatter_pie(
    x: List[float],
    y: List[float],
    pie_size: List[float],
    labels: List[str],
    size: float,
    display_axis=True,
    adjust_y = 0
) -> None:
    fig, ax = plt.subplots(figsize=(12, 10))
    for i in range(len(x)):
         # for my data, there are only two slices for each pie chart
        p_size = [pie_size[i], 1 - pie_size[i]]
        draw_pie(p_size, x[i], y[i], size, ax)

    for i, txt in enumerate(labels):
        ax.annotate(
            txt,
            (x[i], y[i] - adjust_y), # want to adjust the y position of each annotation
            fontproperties=cur_font,
            ha="center",
            va="top",
            fontsize=14,
        )

    ax.axes.get_xaxis().set_visible(display_axis)
    ax.axes.get_yaxis().set_visible(display_axis)
    plt.show()

0 个答案:

没有答案