【问题标题】:matplotlib - making labels for violin plotsmatplotlib - 为小提琴图制作标签
【发布时间】:2015-11-23 06:01:34
【问题描述】:

我通常使用方法'bar'中的参数'label'以以下方式为条形制作标签。

axes[0].bar(x, y, bar_width, label='abc')
axes[0].legend()

现在我想绘制小提琴图并为每个集合制作标签,如下所示,但它不起作用,因为'violinplot'没有参数'label'。

axes[0].violinplot(data1, label='abc1')
axes[1].violinplot(data2, label='abc2')

谁能帮我为每个系列制作一个标签?

【问题讨论】:

标签: python matplotlib label


【解决方案1】:

这是我对多小提琴情节的解决方案。请注意,它从给定小提琴图的第一个阴影区域获取补丁颜色 --- 如果有多种颜色,可以将其更改为执行其他操作,或者您可以使用 violin["cbars"].get_color().flatten() 获取垂直条的颜色。

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

labels = []
def add_label(violin, label):
    color = violin["bodies"][0].get_facecolor().flatten()
    labels.append((mpatches.Patch(color=color), label))


positions = np.arange(3,13,3)
data = np.random.randn(1000, len(positions))
add_label(plt.violinplot(data, positions), "Flat")    

positions = np.arange(1, 10, 2)
data = np.random.randn(1000, len(positions)) + positions
add_label(plt.violinplot(data, positions), "Linear")

positions = np.arange(2, 11, 1)
data = np.random.randn(1000, len(positions)) + positions ** 2 / 4
add_label(plt.violinplot(data, positions), "Quadratic")

plt.legend(*zip(*labels), loc=2)

【讨论】:

    【解决方案2】:

    正如评论中提到的,matplotlib 中的某些图不支持图例。文档仍然提供了一种为它们添加自定义图例的简单方法:http://matplotlib.org/users/legend_guide.html#proxy-legend-handles

    主要思想:添加'fake'对象,这些对象不能在图中显示,然后用它来形成图例方法的句柄列表。

        import random
        import numpy as np
        import matplotlib.pyplot as pl
        import matplotlib.patches as mpatches
        from itertools import repeat
    
        red_patch = mpatches.Patch(color='red')
        # 'fake' invisible object
    
        pos   = [1, 2, 4, 5, 7, 8]
        label = ['plot 1','plot2','ghi','jkl','mno','pqr']
        data  = [np.random.normal(size=100) for i in pos]
    
        fake_handles = repeat(red_patch, len(pos))
    
        pl.figure()
        ax = pl.subplot(111)
        pl.violinplot(data, pos, vert=False)
        ax.legend(fake_handles, label)
        pl.show()
    

    【讨论】:

    • 感谢您的帮助。正如你所说,我添加了假手柄,看起来效果很好。顺便问一下,“Patch”方法中的参数“label”在你的代码中是做什么的?在我看来,根据价值没有任何变化。
    • @HanulLee,我修复了它(通过删除)。它在legend 方法调用中被覆盖,这就是它没有任何改变的原因。
    【解决方案3】:

    有一个比@Ian Hincks 代码更简单的解决方案,无需使用mpatches

    import matplotlib.pyplot as plt
    import numpy as np
    
    positions = np.arange(3,13,3)
    data = np.random.randn(1000, len(positions))
    vp1 = plt.violinplot(data, positions) 
    
    positions = np.arange(1, 10, 2)
    data = np.random.randn(1000, len(positions)) + positions
    vp2 = plt.violinplot(data, positions)
    
    positions = np.arange(2, 11, 1)
    data = np.random.randn(1000, len(positions)) + positions ** 2 / 4
    vp3 = plt.violinplot(data, positions)
    
    plt.legend([vp1['bodies'][0],vp2['bodies'][0], vp3['bodies'][0]], ['flat', 'linear', 'quadratic'], loc=2)[enter image description here][1]
    

    要使用线条代替正文,请将 vp1['bodies'][0] 替换为 vp1['cbars']

    演示:violin plot with labels

    【讨论】:

      【解决方案4】:

      编辑:抱歉,我现在看到您想添加图例,而不是轴标签...

      您可以手动设置刻度位置,然后覆盖它们的标签:

      import numpy as np
      import matplotlib.pyplot as pl
      
      pos   = [1, 2, 4, 5, 7, 8]
      label = ['abc','def','ghi','jkl','mno','pqr']
      data  = [np.random.normal(size=100) for i in pos]
      
      pl.figure()
      ax = pl.subplot(111)
      pl.violinplot(data, pos, vert=False)
      ax.set_yticks(pos)
      ax.set_yticklabels(label)
      

      【讨论】:

      • 感谢您的好意。正如你已经提到的,我正在寻找添加图例的方法。再次感谢。
      【解决方案5】:

      更简洁明了的解决方案可以是:

      plt.style.use('seaborn')
      import matplotlib.pyplot as plt
      labels = ['df=9' , 'df=99', 'df=999', 'df=9999', 'N($\mu=0$, $\sigma=2)$']
      colors = ['orange', 'lightblue', 'lightgreen', 'yellow', 'green']
      def make_violinplot(x, labels, colors):
          parts = plt.violinplot(x, showmeans=True, showmedians=True)
          for body, color in zip(parts['bodies'],colors):
              body.set_facecolor(color)
              parts['cmeans'].set_color('red')
              parts['cmedians'].set_color('blue')
          plt.legend(label[enter image description here][1]s, loc='upper left')
          plt.xticks(np.arange(1, len(labels)+1), labels)
          plt.title("probability density plots t- vs normal distribution")
          plt.rcParams["figure.figsize"] = [8,8]
          return
      make_violinplot(t_dists, labels, colors)
      

      【讨论】:

        猜你喜欢
        • 2015-06-28
        • 1970-01-01
        • 2017-12-01
        • 1970-01-01
        • 2017-08-30
        • 2017-05-13
        • 2023-03-06
        • 2017-09-03
        • 1970-01-01
        相关资源
        最近更新 更多