【问题标题】:Print exact variable values with percentage symbols on pie chart在饼图上打印带有百分比符号的精确变量值
【发布时间】:2023-01-11 16:33:04
【问题描述】:

我想在饼图上用百分比符号(100% 而不是 100.0)表示“百分比答案”列的完全相同的值。我在Stackoverflow上研究了类似的问题,他们似乎使用autopct。我似乎没有正确使用它(我也不理解)来显示我列的相同值,使用 %。

在此先感谢您的帮助!

这是一个小的可重现代码:

# Import pandas library
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
 
# initialize list of lists
data = [['Basics 1', 100.0], ['Basics 2', 100.0], ['Basics 3', 40.0]]
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Course', 'Percentage Answers'])

# Plot teachers feedback percentages
my_labels= list(df['Course'])
plt.pie(df["Percentage Answers"], labels = my_labels, autopct='%0.0f%%')
plt.title("Percentage of Teacher's Feedback Participation")
plt.axis('equal')
plt.show()

【问题讨论】:

  • 请提供完全可重现的代码(即带有数据的代码,可以复制粘贴并运行以生成当前图形)
  • autopct 的百分比是饼图的分数,其中整个饼图代表 100%:如果您想显示其他内容,可以将其作为标签的一部分。您能否添加可重现的数据(以文本形式)和您尝试更改标签的代码(也是以文本形式)?
  • 我只是在我的描述中添加了一个小代码。在此先感谢您的帮助 :)

标签: python matplotlib pie-chart


【解决方案1】:

你可以这样使用,我会告诉你我自己的例子,但你可以简单地应用到你的例子

import matplotlib.pyplot as plt
import numpy


# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs', 'Tgs', 'Lgs'
sizes = [65, 30, 45, 10, 34, 44]

dic = dict()
for i in sizes:
    dic[numpy.round(i / sum(sizes) * 100,2)] = str(int(i)) + " %"

def raw_value(val):
    return dic[numpy.round(val,2)]

fig1, ax1 = plt.subplots()
ax1.pie(sizes,labels=labels, autopct=raw_value)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多