根据返回数据创建饼图

时间:2018-09-27 03:10:41

标签: python

我为一个学校项目创建了一个日志回报变量,现在需要制作一个饼图,将其细分为以下回报百分比:

  • <= -0.02
  • -0.02 <=返回<= 0

是否有一种简单的方法可以将数据分组到变量中,然后将其绘制在饼图中?

1 个答案:

答案 0 :(得分:0)

您主要需要对这些不同的回报百分比类别进行分组。 假设所有这些都存在于数据框中,则可以创建一个新列,称为Return_category,并为您的返回级别提供4个类。 然后,您需要计算这些类别中每个类别有多少 然后,您可以绘制饼图。.

df['Return_Category'] = np.where(df['Pct'] <= -0.2, 'Very Negative',
                                                 np.where(df['Pct'] <=0, 'Marginally Negative',
                                                          np.where(df['Pct'] <= 0.2, 'Marginally Positive', 'Very Positive')))

counts = df['Return_Category'].value_counts()

import matplotlib.pyplot as plt

# Data to plot
labels = 'Very Negative', 'Marginally Negative', 'Marginally Positive', 'Very Positive'
sizes = counts
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0)  # explode 1st slice

# Plot
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
    autopct='%1.1f%%', shadow=True, startangle=140)

plt.axis('equal')
plt.show()