如何为每个箱线图设置不同的颜色

2023-12-29

我正在尝试在 VSCode 中制作 Seaborn 箱线图。我的代码基于这里的示例:here https://github.com/bvalgard/Boxplots/blob/master/Boxplots.ipynb。我专门制作了类似倒数第二个示例的内容,但没有注释。

Code:

# 0. Import the modules
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns


# 1. Import the data
random_df = pd.DataFrame(data = {'0': np.random.rand(10),
                                 '1': np.random.rand(10),
                                 '2': np.random.rand(10),
                                 '3': np.random.rand(10),
                                 '4': np.random.rand(10)})

# 2. Do the plotting

# set style - When adding multple boxplots I like use whitegird 
sns.set(style='whitegrid')

fig, ax = plt.subplots(figsize=(12,9))
g = sns.boxplot(data = random_df, width = 0.7)              

# with a descriptive title a ylabel might not be necessary
plt.ylabel("Accuracy", fontsize = 14)

# X tick-labels
# we are including this because I want the full product name not the variable name
xvalues = ["Label 1", "Label 2", "Label 3", "Label 4", "Label 5"] 

# set xvalues as xtick values
plt.xticks(np.arange(5), xvalues)

# remove all borders except bottom
sns.despine(top=False,
            right=True,
            left=True,
            bottom=False)

# Set colors of box plots 
palette= ['plum','g','orange','b','r']
color_dict = dict(zip(xvalues, palette))

for i in range(0,5):
    mybox = g.artists[i]
    mybox.set_facecolor(color_dict[xvalues[i]])  

plt.tight_layout()
plt.show()

Problem:

当我在 VSCode 中运行代码时,出现以下错误:“索引超出范围”。这与该行有关g.artists[i];当我接受那个的时候for循环出我的代码,然后箱形图就可以工作。另外,当我在 VSCode 中使用此代码时,它只会产生错误。当我在 Google Colab 中运行代码时,没有错误。


在 matplotlib 3.5 中,盒子存储在ax.patches代替ax.artists.

在 Seaborn 中更改颜色的推荐方法是将数据帧转换为长表 https://seaborn.pydata.org/tutorial/data_structure.html#long-form-vs-wide-form-data通过熊猫'melt() https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html然后使用hue=在同一个变量上x=和...一起palette=. (palette其中可以是字典或颜色列表。)

通过临时更改列名称,将自动设置 x 刻度标签。如果ax已预先创建,将其作为参数传递告诉seaborn绘制到该斧头上。 (轴级 https://seaborn.pydata.org/tutorial/function_overview.html#figure-level-vs-axes-level-functions函数返回ax情节创建于其上;当。。。的时候ax作为参数给出,不需要存储返回值。)

这是一个例子:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

random_df = pd.DataFrame(data={'0': np.random.rand(10),
                               '1': np.random.rand(10),
                               '2': np.random.rand(10),
                               '3': np.random.rand(10),
                               '4': np.random.rand(10)})
sns.set(style='whitegrid')

fig, ax = plt.subplots(figsize=(12, 9))
xvalues = ["Label 1", "Label 2", "Label 3", "Label 4", "Label 5"]
palette = ['plum', 'g', 'orange', 'b', 'r']

melted_df = random_df.set_axis(xvalues, axis=1).melt(var_name='Variable', value_name='Accuracy')
sns.boxplot(data=melted_df, x='Variable', y='Accuracy', hue='Variable', palette=palette,
            width=0.7, dodge=False, ax=ax)

ax.legend_.remove()  # remove the legend, as the information is already present in the x labels
ax.set_xlabel('')  # remove unuseful xlabel ('Variable')
ax.set_ylabel("Accuracy", fontsize=14)

sns.despine(top=True, right=True, left=True, bottom=False)
plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为每个箱线图设置不同的颜色 的相关文章

  • 如何将 Google Cloud Storage 中的许多文件设为私有?

    我进行了很多研究 但无法为此提出解决方案 以下是我用来在 GCP 中公开所有文件的代码 def make blob public bucket name blob name Makes a blob publicly accessible
  • python blpapi安装错误

    我试图根据 README 中的说明为 python 安装 blpapi 3 5 5 但是在运行时 python setup py install 我收到以下错误 running install running build running b
  • 从 Django 基于类的视图的 form_valid 方法调用特殊(非 HTTP)URL

    如果你这样做的话 有一个 HTML 技巧 a href New SMS Message a 点击新短信打开手机的本机短信应用程序并预 先填写To包含所提供号码的字段 在本例中为 1 408 555 1212 以及body与提供的消息 Hel
  • 如何计算查询集中每个项目的两个字段的总和

    假设我有以下模型结构 class SomeModel Model base price DecimalField commision DecimalField 我不想存储total price在我的数据库中为了数据一致性并希望将其计算为ba
  • 如何在seaborn中绘制离散变量的分布图

    当我画画的时候displot对于离散变量 分布可能不像我想象的那样 例如 We can find that there are crevices in the barplot so that the curve in kdeplot is
  • Django 说“id 可能不为 NULL”,但为什么会这样呢?

    我今天要疯了 我只是尝试插入一条新记录 但它返回了 post blogpost id 可能不为 NULL 错误 这是我的模型 class BlogPost models Model title models CharField max le
  • Python ElementTree 获取带有命名空间的属性

    我试图访问 XML 中的 def 所以在这个例子中我会得到Evolus Common PlainTextV2作为输出 我似乎无法弄清楚如何获取具有名称空间的属性 如果我想得到id它工作得很好 Python for content ns in
  • 从 Spark 数据帧中过滤大量 ID

    我有一个大型数据框 其格式类似于 ID Cat date 12 A 201602 14 B 201601 19 A 201608 12 F 201605 11 G 201603 我需要根据大约 500 万个 Is 的列表来过滤行 最直接的方
  • 监控培训课程如何运作?

    我试图理解使用之间的区别tf Session and tf train MonitoredTrainingSession 以及我可能更喜欢其中之一 似乎当我使用后者时 我可以避免许多 杂务 例如初始化变量 启动队列运行程序或设置文件编写器以
  • 如何解决CDK CLI版本不匹配的问题

    我收到以下错误 此 CDK CLI 与您的应用程序使用的 CDK 库不兼容 请将CLI升级到最新版本 云程序集架构版本不匹配 支持的最大架构版本为 8 0 0 但发现为 9 0 0 发出后cdk diff命令 我确实跑了npm instal
  • Python 在 64 位 vista 上获取 os.environ["ProgramFiles"] 的错误值

    Vista64 计算机上的 Python 2 4 3 环境中有以下2个变量 ProgramFiles C Program Files ProgramFiles x86 C Program Files x86 但是当我运行以下命令时 impo
  • Python:绘制甘特图的模块

    有没有一个好的Python绘图模块甘特图 http en wikipedia org wiki Gantt chart 我试过了开罗情节 http linil wordpress com 2008 09 16 cairoplot 11 但它
  • telethon 库:如何通过电话号码添加用户

    我正在研究 Telegram 的 Telethon 库 它可以使用 Telegram API 充当 Telegram 客户端 重要提示 这是电报客户端 API https core telegram org telegram api 而不是
  • 安塞布尔 + 10.11.6

    我在 非常 干净地安装 10 11 6 时遇到了 Ansible 的奇怪问题 我已经安装了brew zsh oh my zsh Lil snitch 和1password 实际上没有安装其他任何东西 我安装了ansible brew ins
  • 在 Python 中将嵌套字典位置作为参数传递

    如果我有一个嵌套字典 我可以通过索引来获取键 如下所示 gt gt gt d a b c gt gt gt d a b c 我可以将该索引作为函数参数传递吗 def get nested value d path a b return d
  • 如何在自定义 django 命令中抽象出命令代码

    我正在我的应用程序下编写自定义 django 命令management commands目录 目前我在该目录中有 6 个不同的文件 每个文件都有不同的命令来解决独特的需求 然而 有一些实用程序是它们所共有的 抽象出这些公共代码的最佳方法是什
  • 使用 conda 安装额外功能

    With pip我们可以使用方括号安装子包 例如与阿帕奇气流 https pythonhosted org airflow installation html pip install airflow all 有类似的东西吗conda或者我必
  • 获取 python 模块的 2 个独立实例

    我正在与以非 OO 方式编写的 python 2 x API 进行交互 它使用模块全局范围来处理一些内部状态驱动的东西 在它不再是单例的情况下需要它 并且修改原始代码 不是我们的 不是一个选择 如果不使用单独解释器的子进程运行 有什么方法可
  • Django INSTALLED_APPS 的命名约定是如何工作的?

    该网站上的教程创建了一个名为 polls 的应用程序 它使用 django 1 9 所以在 INSTALLED APPS 中它是 polls apps PollsConfig 我正在观看一个教程 他将应用程序命名为新闻通讯 并且在 INST
  • 给定一个字符串,如何删除所有重复的连续字母?

    如何从字符串中删除两个连续的字母 例如 a str hii thherre 应该成为 hi there 我尝试这样做 a str join sorted set a str key a str index 但是 我得到 hi ter 是的

随机推荐