带seaborn的条形图,按行着色

2023-12-01

我创建了一个组合条形图,无法按行着色。我尝试了色调、颜色、调色板、库的所有组合,但没有成功。我的代码是:

fig, axes=plt.subplots(1,5,figsize=(11,8))
my_new_color={'UA':'white','AA':'blueviolet','US':'#98F5FF',
         'F9':'#FF9912','B6':'#66CD00','OO':'green','AS':'#3D59AB','NK':'black',
         'WN':'red','DL':'yellow','EV':'#98F5FF','HA':'#FFF8DC','MQ':'#7FFF00',
         'VX':'pink'}

sns.boxplot(ax=axes[0],y='AIR_SYSTEM_DELAY', data=ARL_DA_reason3,linewidth=1, width=0.55)
sns.stripplot(ax=axes[0],y='AIR_SYSTEM_DELAY', data=ARL_DA_reason3, size=10, color='yellow')

sns.boxplot(ax=axes[1], data=ARL_DA_reason3, y='SECURITY_DELAY',linewidth=1, width=0.55)
sns.stripplot(ax=axes[1],y='SECURITY_DELAY', data=ARL_DA_reason3, color='yellow',size=10)

sns.boxplot(ax=axes[2], data=ARL_DA_reason3, y='AIRLINE_DELAY',linewidth=1, width=0.55)
sns.stripplot(ax=axes[2],y='AIRLINE_DELAY', data=ARL_DA_reason3, color='yellow',size=10)

sns.boxplot(ax=axes[3], data=ARL_DA_reason3, y='LATE_AIRCRAFT_DELAY',linewidth=1, width=0.55)
sns.stripplot(ax=axes[3],y='LATE_AIRCRAFT_DELAY', data=ARL_DA_reason3, color='yellow',size=10)

sns.boxplot(ax=axes[4], data=ARL_DA_reason3, y='WEATHER_DELAY',linewidth=1, width=0.55)
sns.stripplot(ax=axes[4],y='WEATHER_DELAY', data=ARL_DA_reason3, color='yellow',size=10)

enter image description here

enter image description here


西伯恩的stripplot()似乎不支持单个点的颜色。然而,一个stripplot()可以通过模拟ax.scatter使用随机抖动的 x 位置。可以通过将给定字典映射到ARL_CODE column.

这是一些示例代码(使用循环以避免代码复制):

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

sns.set()
my_new_color = {'UA': 'white', 'AA': 'blueviolet', 'US': '#98F5FF', 'F9': '#FF9912', 'B6': '#66CD00', 'OO': 'green',
                'AS': '#3D59AB', 'NK': 'black', 'WN': 'red', 'DL': 'yellow', 'EV': '#98F5FF', 'HA': '#FFF8DC',
                'MQ': '#7FFF00', 'VX': 'pink'}
# create some test data similar to the OP
df = pd.DataFrame({'ARL_CODE': np.random.choice(list(my_new_color.keys()), 50),
                   'AIR_SYSTEM_DELAY': np.random.uniform(100000, 1800000, 50),
                   'SECURITY_DELAY': np.random.uniform(1000, 17000, 50),
                   'AIRLINE_DELAY': np.random.uniform(100000, 4000000, 50)})
colors = df['ARL_CODE'].map(my_new_color)

y_columns = ['AIR_SYSTEM_DELAY', 'SECURITY_DELAY', 'AIRLINE_DELAY']
fig, axes = plt.subplots(ncols=len(y_columns), figsize=(11, 8))

for y_col, ax in zip(y_columns, axes):
    sns.boxplot(y=y_col, data=df, linewidth=1, width=0.55, ax=ax)
    ax.scatter(x=np.random.uniform(-0.2, 0.2, len(df)), y=df[y_col], s=100, color=colors)
    ax.set_ylabel('')
    ax.set_title(y_col)
plt.tight_layout()
plt.show()

combining sns.stripplot and sns.boxplot

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

带seaborn的条形图,按行着色 的相关文章

随机推荐