Pie plot labeling in python

28 views Asked by At

I want make pie plot but some of wedege in plot are as very low percetage so i tried to label them out side the plot with arrow outside the plot but i getiing wrong not able to label them properly this is the code

def create_pie_plot(sample_id, data, column_name, threshold=0.05): # Filter data for the selected sample and abundance over the threshold filtered_data = data[(data['Sample'] == sample_id) & (data[column_name] > threshold)]

# Resetting the index to avoid potential KeyError
filtered_data.reset_index(drop=True, inplace=True)

# Increase figure size
fig, ax = plt.subplots(figsize=(8, 8))

# Create the pie plot with explode
wedges, texts, autotexts = ax.pie(
    x=filtered_data[column_name],
    autopct='%1.1f%%',
    pctdistance=0.5,
    textprops=dict(color="w")
)


# Add labels with arrows for percentage < 1%
kw = dict(arrowprops=dict(arrowstyle="-"), bbox=dict(boxstyle="round,pad=0.3", edgecolor="none", facecolor="none"))
for i, p in enumerate(wedges):
    percentage = filtered_data[column_name].iloc[i]
    if percentage < 1:
        ang = (p.theta2 - p.theta1)/2. + p.theta1
        y = np.sin(np.deg2rad(ang))
        x = np.cos(np.deg2rad(ang))
        horizontalalignment = {-1: "right", 0: "center", 1: "left"}[int(np.sign(x))]
        connectionstyle = f"angle,angleA=0,angleB={ang}"
        kw["arrowprops"].update({"connectionstyle": connectionstyle})
        ax.annotate(f"{percentage:.1f}%", xy=(x, y), xycoords='data', xytext=(1.35*np.sign(x), 1.4*y),
                    textcoords='data', horizontalalignment=horizontalalignment, **kw)

# Manually adjust layout parameters
plt.subplots_adjust(left=0.1, right=0.6)  # Adjust left and right margins

# Update layout
ax.set_title(f"Pie Plot for Sample: {sample_id}")

# Show the plot
plt.show()

This plot i getting

how can adjust this arrows so i can lable the value outside the wedges whoes percentage is below 1 percent

0

There are 0 answers