【问题标题】:Create donut using pie chart with custom labels使用带有自定义标签的饼图创建甜甜圈
【发布时间】:2020-01-27 23:11:17
【问题描述】:

我正在处理财务数据,我打算弄清楚如何在我的数据上创建嵌套饼图。具体来说,我过滤了导出和导入产品数据并为其渲染嵌套图。我确实为每个渲染饼图,我无法为数据获得正确的嵌套饼图或圆环图。我在SO 上查看了可能的帖子,但没有找到任何线索如何获取我的情节。

我目前的输出

import pandas as pd
from matplotlib import pyplot as plt

df5=df_from_gist_exp.groupby(['cty_ptn'])['qty1'].sum().nlargest(10)
df6=df_from_gist_imp.groupby(['cty_ptn'])['qty1'].sum().nlargest(10)
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.pie(df5, labels=df5.index, autopct='%1.0f%%', radius=1)
ax2.pie(df6, labels=df6.index, autopct='%1.0f%%', radius=1)
plt.axis('equal')
plt.tight_layout()
plt.show()

当前情节

运行上述解决方案后我得到了这个情节:

想要的情节

其实我想用同样的数据来渲染这个饼图或者圆环图:

我怎样才能得到这个情节?有什么诀窍可以做到这一点吗?谢谢

【问题讨论】:

  • 嵌套饼图matplotlib.org/3.1.0/gallery/pie_and_polar_charts/…看起来像你想要的
  • 我无法重新创建您的变量df_from_gist,而无需付出相当大的努力。你能把它放在托管在 github 上的 google colab 或 python notebook 中吗?我对 matplotlib 不够熟悉,无法从内存中解决这个问题。祝你好运!
  • 获取居中的文本很容易。 plt.text(0, 0, '960 K', fontsize=..., ha='center', va='bottom')。尝试找到metric tons 的最佳位置。如果您想要一个完全自动化的解决方案,定位所有其他文本是一项相当大的工作。否则,只需搜索最佳位置。
  • @Jerry 请向 shanecandoit 提供所有必需的信息。阅读creating a minimal reproducible example
  • 来自 gist 的数据似乎是 1000 行,全部来自阿根廷。 df_export 和 df_import 为空。请执行print(df5.to_dict()) 并将结果粘贴到您的问题中。 df6 也一样。然后删除所有其他 pandas 和 csv 代码,因为它们对于饼图并不重要。还要添加print(df_export['qty1'].sum()) 的输出,与导入相同。

标签: python matplotlib charts


【解决方案1】:

我只是做了一个最小的代码来实现你想要的:

import matplotlib.pyplot as plt
import numpy as np

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
lbls = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]

# Intended to serve something like a global variable
class MyClass:
    i = -1

def func(pct, labels, vals):
    MyClass.i +=1
    # Returns absolute value against the default percentage
    # absolute = int(pct/100.*np.sum(vals))
    # Combine labels and values
    return "{:s}\n{:.0f} %".format(labels[MyClass.i], pct)


fig1, ax1 = plt.subplots()
# Pie wedgeprops with width being the donut thickness
ax1.pie(sizes, wedgeprops=dict(width=0.7), autopct=lambda pct: func(pct, lbls, sizes),
        shadow=True, startangle=90)
sumstr = 'Total = '+str(np.sum(sizes))
# String on the donut center
ax1.text(0., 0., sumstr, horizontalalignment='center', verticalalignment='center')
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

这会产生以下图表:

【讨论】:

  • @Jerry 请将您阅读要点的确切方式添加到问题的代码中。
  • 把你分配df_from_gist的位放在答案中,也许。同样从文件中取出必要的行并将它们放在一个字符串中对于半路会见人大有帮助。我希望这个建议会有所帮助,我知道这样的调试可能会令人沮丧。
  • @Jerry :这是一个完全不同的故事。尝试一些关于如何使用 pandas 完成数据帧的教程。网上有很多。一旦你掌握了它,将上面的情节代码插入你的代码。它现在在甜甜圈中心有总和。
猜你喜欢
  • 1970-01-01
  • 2015-03-07
  • 2012-07-22
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多