Python Matplotlib 箱线图颜色 [英] Python Matplotlib Boxplot Color

查看:306
本文介绍了Python Matplotlib 箱线图颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Matplotlib 制作两组箱线图.我希望用不同的颜色填充每组箱线图(以及点和胡须).所以基本上剧情上会有两种颜色

我的代码在下面,如果您能帮助制作这些彩色图,那就太好了.d0d1 分别是数据列表的列表.我想要用一种颜色的 d0 数据制作的箱线图,以及另一种颜色的 d1 数据制作的箱线图.

plt.boxplot(d0, widths = 0.1)plt.boxplot(d1, 宽度 = 0.1)

解决方案

要为箱线图着色,您需要首先使用 patch_artist=True 关键字来告诉它这些方框是补丁,而不仅仅是路径.那么你在这里有两个主要选择:

  1. 通过...props 关键字参数设置颜色,例如
    boxprops=dict(facecolor="red").对于所有关键字参数,请参阅

    I am trying to make two sets of box plots using Matplotlib. I want each set of box plot filled (and points and whiskers) in a different color. So basically there will be two colors on the plot

    My code is below, would be great if you can help make these plots in color. d0 and d1 are each list of lists of data. I want the set of box plots made with data in d0 in one color, and the set of box plots with data in d1 in another color.

    plt.boxplot(d0, widths = 0.1)
    plt.boxplot(d1, widths = 0.1)
    

    解决方案

    To colorize the boxplot, you need to first use the patch_artist=True keyword to tell it that the boxes are patches and not just paths. Then you have two main options here:

    1. set the color via ...props keyword argument, e.g.
      boxprops=dict(facecolor="red"). For all keyword arguments, refer to the documentation
    2. Use the plt.setp(item, properties) functionality to set the properties of the boxes, whiskers, fliers, medians, caps.
    3. obtain the individual items of the boxes from the returned dictionary and use item.set_<property>(...) on them individually. This option is detailed in an answer to the following question: python matplotlib filled boxplots, where it allows to change the color of the individual boxes separately.

    The complete example, showing options 1 and 2:

    import matplotlib.pyplot as plt
    import numpy as np
    data = np.random.normal(0.1, size=(100,6))
    data[76:79,:] = np.ones((3,6))+0.2
    
    plt.figure(figsize=(4,3))
    # option 1, specify props dictionaries
    c = "red"
    plt.boxplot(data[:,:3], positions=[1,2,3], notch=True, patch_artist=True,
                boxprops=dict(facecolor=c, color=c),
                capprops=dict(color=c),
                whiskerprops=dict(color=c),
                flierprops=dict(color=c, markeredgecolor=c),
                medianprops=dict(color=c),
                )
    
    
    # option 2, set all colors individually
    c2 = "purple"
    box1 = plt.boxplot(data[:,::-2]+1, positions=[1.5,2.5,3.5], notch=True, patch_artist=True)
    for item in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
            plt.setp(box1[item], color=c2)
    plt.setp(box1["boxes"], facecolor=c2)
    plt.setp(box1["fliers"], markeredgecolor=c2)
    
    
    plt.xlim(0.5,4)
    plt.xticks([1,2,3], [1,2,3])
    plt.show()
    

    这篇关于Python Matplotlib 箱线图颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆