如何向matplotlib pichart绘图中的图例添加百分比

2024-05-29 10:46:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个简单的脚本,它读取一个CSV文件列,创建一个包含类别的新列,然后生成一个piechart。当前,piechart已将百分比附加到每个楔块

如何将百分比移动到图例?

是否有办法将autopct='%1.1f%%'参数移动到图例中?

以下是显示当前pi图表输出的图像:

Pichart output

下面是我的python代码和示例数据

import pandas as pd
import matplotlib.pyplot as plt
import os

# Setup file paths
file_name = "Software.csv"
dirname = os.getcwd()
file_path = os.getcwd() + "\\" + file_name
df = pd.read_csv(file_path)

# Name output file
split_path = file_path[:-4]
output_file = split_path + "_output.csv"

def check_lines(x):
    if 'Microsoft' in x:
        return 'Microsoft'
    elif 'Google' in x:
        return 'Google'
    elif 'Adobe' in x:
        return 'Adobe'
    elif 'Mozilla' in x:
        return 'Mozilla'
    elif 'Apple' in x:
        return 'Apple'
    elif 'Amazon' in x:
        return 'Amazon'
    else:
        return 'Other'

# Create a new column series; Apply the function to it.
df['Category'] = df['Title'].apply(check_lines)

# Create output file
df.to_csv(output_file)

# -- Pi Chart Version 2 -- 
df2 = pd.read_csv(output_file)
df2val = df2.value_counts('Category')

# Create PI Chart
plot = df2val.plot.pie(y='Category', autopct='%1.1f%%', labeldistance=None, startangle=0)
plt.ylabel('')
plt.legend(title="Categories", bbox_to_anchor=(1.05,0.5), loc="center right", fontsize=10, bbox_transform=plt.gcf().transFigure)

# Save Pi Chart
plt.savefig(split_path + "_chart.png", bbox_inches="tight")
plt.show()

样本数据:

Title
Amazon Chime
Mozilla Firefox
Adobe Photoshop
Adobe Photoshop
Adobe Photoshop
Adobe Photoshop
Adobe Reader
Adobe Reader
Adobe Reader
Adobe Reader
Adobe Reader
Adobe Reader
Adobe Reader
Apple Safari
Apple Safari
Apple Safari
Google Drive
Microsoft Word
Microsoft OneDrive
Wireshark
Notepad
Notepad
Notepad
7zip
7zip
7zip
7zip
7zip
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge

Tags: csvpathinappledfoutputreturnplt
2条回答

您可以以字符串格式存储df2的索引和值,并将其用作plt.legend()标签参数(例如,在名为legend的变量中分配标签,稍后使用)

df2.plot.pie(labeldistance=None)
plt.ylabel('')

legend = ['{} ({:.2%})'.format(idx, value) for idx, value in zip(df2.index, df2.values)]
plt.legend(legend, title="Categories", bbox_to_anchor=(1.05,0.5), loc="center right", fontsize=10, bbox_transform=plt.gcf().transFigure)

plt.show()

enter image description here

您可以按如下方式计算百分比,并将其添加到图例中:

plot = df2val.plot.pie(y='Category',  startangle=0)
plt.ylabel('')
percents = df2val.to_numpy() * 100 / df2val.to_numpy().sum()
plt.legend( bbox_to_anchor=(1.35,1.1), loc='upper right',
            labels=['%s, %1.1f %%' % (l, s) for l, s in zip(df2val.index,percents)])

enter image description here

相关问题 更多 >

    热门问题