【问题标题】:How to iteratively plot different data as boxplots in seaborn (without them overlapping)?如何在seaborn中将不同的数据迭代地绘制为箱线图(没有重叠)?
【发布时间】:2018-01-09 21:29:40
【问题描述】:

有没有一种方法可以使用seabornsns.boxplot() 迭代地绘制数据而不会使箱线图重叠? (没有将数据集组合成一个pd.DataFrame()

背景

有时在比较不同(例如大小/形状)的数据集时,相互比较通常很有用,可以通过使用不同的共享变量(通过pd.cut()df.groupby(),如下所示)对数据集进行分箱来进行。

以前,我通过使用matplotlibax.boxplot() 循环单独的DataFrames(通过提供y 轴位置值作为position 参数以确保箱线图不要重叠)。

示例

下面是一个简化示例,显示了使用sns.boxplot() 时的重叠图:

import seaborn as sns
import random
import pandas as pd
import matplotlib.pyplot as plt

# Get the tips dataset and select a subset as an example
tips = sns.load_dataset("tips")
variable_to_bin_by = 'tip'
binned_variable = 'total_bill'
df = tips[[binned_variable,  variable_to_bin_by] ]

# Create a second dataframe with different values and shape
df2 = pd.concat( [ df.copy() ] *5 )    
# Use psuedo random numbers to convey that df2 is different to df
scale = [ random.uniform(0,2) for i in range(len(df2[binned_variable])) ]  
df2[ binned_variable ] = df2[binned_variable].values * scale * 5
dfs = [ df, df2 ]

# Group the data by a list of bins
bins = [0, 1, 2, 3, 4]
for n, df in enumerate( dfs ):
    gdf = df.groupby( pd.cut(df[variable_to_bin_by].values, bins ) )
    data = [ i[1][binned_variable].values  for i in gdf]
    dfs[n] = pd.DataFrame( data, index = bins[:-1])

# Create an axis for both DataFrames to be plotted on
fig, ax = plt.subplots()

# Loop the DataFrames and plot
colors = ['red', 'black']    
for n in range(2):
    ax = sns.boxplot( data=dfs[n].T, ax=ax, width=0.2, orient='h', 
                      color=colors[n] )
plt.ylabel( variable_to_bin_by )
plt.xlabel( binned_variable )
plt.show()

更多细节

我意识到上面的简化示例可以通过组合 DataFrame 并将 hue 参数提供给 sns.boxplot() 来解决。

更新提供的 DataFrames 的索引也无济于事,因为随后使用了提供的最后一个 DataFrame 的 y 值。

提供kwargs 参数(例如kwargs={'positions': dfs[n].T.index})将不起作用,因为这会引发TypeError

TypeError: boxplot() 获得了多个关键字参数值 '职位'

sns.boxplot()dodge 参数设置为True 并不能解决这个问题。

【问题讨论】:

  • 你需要在循环中创建plt设置,在sns.boxplot之前和之后
  • 通常的策略确实是将数据合并到一个数据帧中。为什么这里没有这个选项?
  • @Mohsen_Fatemi,请提供您推荐更新的设置?
  • @ImportanceOfBeingErnest 确实如此。我已根据您的评论更新了示例,以尝试突出显示此示例中的 DataFrame 在形状和内容上有所不同。

标签: python matplotlib plot seaborn boxplot


【解决方案1】:

有趣的是,我提出的“hack”earlier today in this answer 可以在这里应用。

这会使代码有点复杂,因为 seaborn 需要一个长格式的数据帧而不是宽格式来使用色调嵌套。

# Get the tips dataset and select a subset as an example
tips = sns.load_dataset("tips")
df = tips[['total_bill',   'tip'] ]

# Group the data by 
bins = [0, 1, 2, 3, 4]
gdf = df.groupby( pd.cut(df['tip'].values, bins ) )
data = [ i[1]['total_bill'].values  for i in gdf]
df = pd.DataFrame( data , index = bins[:-1]).T
dfm = df.melt() # create a long-form database
dfm.loc[:,'dummy'] = 'dummy'

# Create a second, slightly different, DataFrame
dfm2 = dfm.copy()
dfm2.value = dfm.value*2
dfs = [ dfm, dfm2 ]
colors = ['red', 'black']
hue_orders = [['dummy','other'], ['other','dummy']]

# Create an axis for both DataFrames to be plotted on
fig, ax = plt.subplots()

# Loop the DataFrames and plot
for n in range(2):
    ax = sns.boxplot( data=dfs[n], x='value', y='variable', hue='dummy', hue_order=hue_orders[n], ax=ax, width=0.2, orient='h', 
                      color=colors[n] )
ax.legend_.remove()
plt.show()

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2023-02-24
  • 2019-11-14
  • 2020-03-08
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
相关资源
最近更新 更多