【问题标题】:Matplotlib box plot fliers not showingMatplotlib 箱线图传单未显示
【发布时间】:2015-04-09 19:08:42
【问题描述】:

我想知道是否有人对 Matplotlib 的箱线图传单没有显示有疑问?

我将这里的示例复制粘贴到 python 脚本中: http://blog.bharatbhole.com/creating-boxplots-with-matplotlib/

...但箱线图传单(异常值)未显示。有谁知道我为什么看不到他们?抱歉,如果这是一个愚蠢的问题,但我一生都无法弄清楚为什么它不起作用。

## Create data
np.random.seed(10)
collectn_1 = np.random.normal(100, 10, 200)
collectn_2 = np.random.normal(80, 30, 200)
collectn_3 = np.random.normal(90, 20, 200)
collectn_4 = np.random.normal(70, 25, 200)

## combine these different collections into a list    
data_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4]

# Create a figure instance
fig = plt.figure(1, figsize=(9, 6))

# Create an axes instance
ax = fig.add_subplot(111)

# Create the boxplot
bp = ax.boxplot(data_to_plot)

我还尝试将showfliers=True 添加到该脚本的最后一行,但它仍然无法正常工作。

这是我得到的输出:

【问题讨论】:

  • 我通过复制粘贴该代码复制了原件。你还有其他加载的吗?网格/背景颜色/单位字体似乎都不标准。
  • 我正在使用 iPython 笔记本......我应该提到它。这可能就是原因。你知道如何将格式设置回默认的 Matplotlib 设置吗?

标签: python matplotlib boxplot seaborn


【解决方案1】:

从你的情节来看,你似乎已经导入了seaborn 模块。有一个 issue 与 matplotlib boxplot 传单在 seaborn 被导入时没有显示,即使传单被明确启用。未导入 seaborn 时,您的代码似乎运行良好:

当 seaborn 被导入时,你可以这样做:

解决方案 1:

假设你已经像这样导入 seaborn:

import seaborn as sns

你可以使用 seaborn boxplot 函数:

sns.boxplot(data_to_plot, ax=ax)

导致:

解决方案 2:

如果你想继续使用 matplotlib boxplot 函数(来自Automatic (whisker-sensitive) ylim in boxplots):

ax.boxplot(data_to_plot, sym='k.')

导致:

【讨论】:

    【解决方案2】:

    如果传单标记设置为None,您可能看不到传单。 page you linked to 有一个 for flier in bp['fliers']: 循环,用于设置传单标记样式、颜色和 alpha:

    import numpy as np
    import matplotlib.pyplot as plt
    
    np.random.seed(10)
    collectn_1 = np.random.normal(100, 10, 200)
    collectn_2 = np.random.normal(80, 30, 200)
    collectn_3 = np.random.normal(90, 20, 200)
    collectn_4 = np.random.normal(70, 25, 200)
    
    ## combine these different collections into a list    
    data_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4]
    
    # Create a figure instance
    fig = plt.figure(1, figsize=(9, 6))
    
    # Create an axes instance
    ax = fig.add_subplot(111)
    
    # Create the boxplot
    bp = ax.boxplot(data_to_plot, showfliers=True)
    
    for flier in bp['fliers']:
        flier.set(marker='o', color='#e7298a', alpha=0.5)
    
    plt.show()
    

    产量

    【讨论】:

    • 奇怪的是,我在运行 OP 的代码时看到了异常值,但在运行您的代码时却没有。你的意思是也有marker=None?将其更改为 marker='o' 会生成您的图表(对我而言)。
    • @jedwards:感谢您的提醒。我用错误的marker 设置复制粘贴了代码。
    • 嗯。是的,我没有得到这样的情节。我认为这是因为我使用的 iPython 笔记本有一种我无法摆脱的奇怪格式。有没有简单的方法来获得传单(离群值)值?我试过查看bp['fliers'],但找不到从中提取值的方法。只要我有这些值,我想我可以将它们绘制在我的箱线图上。
    • 您可以从[line.get_data() for line in bp['fliers']] 获取坐标,但应该有一种方法可以配置 IPython 或 matplotlib/seaborn 以自动显示传单。
    猜你喜欢
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 2010-12-03
    • 2018-07-12
    相关资源
    最近更新 更多