我尝试生成一个嵌套饼图作为下面的例子。但是,文本位置看起来并不像它应该的那样漂亮。我想调整内部饼图中的文本位置,使其适合饼图的内部(最好沿着红线,但如果它在内部并且看起来很好就好了)。此外,我想删除一部分饼图的轮廓在下面的图片。任何帮助都会很有帮助。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data=pd.read_csv(r"https://raw.githubusercontent.com/tuyenhavan/Course_Data/main/test_pie_chart.csv")
# Get outer and inner counts
inner=data.groupby(["Col1"]).size()
outer=data.groupby(["Col1","Col2"]).size()
# Get outer and inner labels
inner_label=[f"{idx} ({val/sum(inner.values.flatten())*100:.2f}%)" for idx, val in zip(inner.index.get_level_values(0),inner.values.flatten())]
outer_label=[f"{idx} ({val/sum(outer.values.flatten())*100:.2f}%)" for idx, val in zip(outer.index.get_level_values(1), outer.values.flatten())]
# Inner and outer colors
inner_color=["#16A085","#808000","#BA4A00"]
outer_color=["#808080","#229954","#34495E","#2E86C1","#CA6F1E","white","#808080","#229954","#CA6F1E","#00FFFF"]
# Set figure size and radius adjustment
fig, ax=plt.subplots(figsize=(10,8))
size=0.4
# Plot the inner pie chart
ax.pie(inner.values.flatten(), labels=inner_label, radius=1-size,wedgeprops=dict(width=size, edgecolor='w'),\
colors=inner_color,textprops ={"fontsize":12},labeldistance=0.4) # labels=inner_label,autopct ='%1.1f%%',
# Plot the outer pie chart
ax.pie(outer.values.flatten(), radius=1, labels=outer_label,wedgeprops=dict(width=size, edgecolor='w'),\
colors=outer_color, textprops={"fontsize":12},labeldistance=1.1)
ax.set(xlim=(-1,1), ylim=(-1,1))
ax.set(aspect="equal")
plt.show()
1条答案
按热度按时间mjqavswn1#
要实现你想要的,你必须玩一点文字标签.可以定位每个楔块和标签。从
ax.pie()
方法返回楔和标签列表。要删除标签,只需将其文本设置为空字符串即可。
为了有更好的内部标签,我建议将百分比移动到新行,然后相应地旋转每个标签。
下面是这样做的代码片段:
导致: