【问题标题】:How to surpress some autopct values plotted on a pie plot如何抑制绘制在饼图上的一些 autopct 值
【发布时间】:2021-12-21 06:18:09
【问题描述】:

我可以创建一个饼图,其中每个楔子的大小都打印如下:

df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],
                   'radius': [2439.7, 6051.8, 6378.1]},
                  index=['Mercury', 'Venus', 'Earth'])
plot = df.plot.pie(y='mass', figsize=(5, 5), autopct= '%.2f')

我怎样才能让它只打印一个子集的值(比如不打印 Mercury)?

【问题讨论】:

    标签: python pandas matplotlib pie-chart


    【解决方案1】:
    df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],
                       'radius': [2439.7, 6051.8, 6378.1]},
                      index=['Mercury', 'Venus', 'Earth'])
    
    autopct = lambda v: f'{v:.2f}%' if v > 10 else None
    
    plot = df.plot.pie(y='mass', figsize=(5, 5), autopct=autopct)
    

    【讨论】:

    • 啊,这比我的回答更干净:)
    【解决方案2】:

    一个选项是在创建绘图后删除文本(或将其设置为不可见)。现在的主要问题是找到要修改的正确文本。例如:

    import pandas as pd
    
    df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],
                       'radius': [2439.7, 6051.8, 6378.1]},
                      index=['Mercury', 'Venus', 'Earth'])
    plot = df.plot.pie(y='mass', figsize=(5, 5), autopct= '%.2f')
    
    print(plot.texts)
    

    会产生

    [Text(1.09526552098778, 0.10194821496900702, 'Mercury'),
     Text(0.5974175569024254, 0.05560811725582201, '2.95'),
     Text(0.01701519685165565, 1.0998683935253797, 'Venus'),
     Text(0.009281016464539445, 0.5999282146502071, '43.60'),
     Text(-0.11887821664562105, -1.0935574834489301, 'Earth'),
     Text(-0.0648426636248842, -0.5964859000630527, '53.45')]
    

    所以你可以看到,这是我们要关闭的第二个Text 项目。一个简单的方法是:

    plot.texts[1].set_visible(False)
    

    或者

    plot.texts[1].remove()
    

    显然,概括这一点的问题是提前知道要删除哪些文本。正如您在上面看到的,将文本添加到轴的顺序是索引名称(行星名称),然后是该行星的 autopct 标签,然后重复下一个行星。因此,如果您知道要删除行星 i 的 autopct 标签,则可以使用 plot.texts[2 * i + 1].remove() 之类的东西。

    为给定的行星标签执行此操作的辅助函数如下所示:

    def remove_text(label):
        ind = df.index.get_loc(label) * 2 + 1
        plot.texts[ind].remove()
    
    remove_text('Mercury')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-03
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多