【问题标题】:How to sequentially add seaborn boxplots to the same axis?如何将seaborn箱线图顺序添加到同一轴?
【发布时间】:2020-06-24 13:18:14
【问题描述】:

有没有办法将多个 seaborn 箱线图按顺序添加到一个图形?

Time-series boxplot in pandas为例:

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

n = 480
ts = pd.Series(np.random.randn(n), index=pd.date_range(start="2014-02-01", periods=n, freq="H"))


fig, ax = plt.subplots(figsize=(12,5))
seaborn.boxplot(ts.index.dayofyear, ts, ax=ax)

这给了我一系列箱线图?

现在,有什么方法可以并排绘制两个类似的时间序列?我想将它绘制在具有 make_new_plot 布尔参数的函数中,用于分离从 for 循环中绘制的箱线图。

如果我尝试在同一轴上调用它,它会给我重叠图:

我知道可以将数据帧连接起来并制作连接数据帧的箱线图,但我不希望这个绘图函数返回任何数据帧。

还有其他方法吗?也许有可能以某种方式操纵盒子的宽度和位置来实现这一点?我需要一个时间序列的箱线图和 matplotlib“位置”参数是 seaborn 故意不支持的,这让我很难弄清楚如何去做。

注意它与例如不一样。 Plotting multiple boxplots in seaborn?,因为我想按顺序绘制它而不从绘图函数返回任何数据帧。

【问题讨论】:

  • 第二组盒子应该在哪里?每个新框并排(如色调嵌套),或作为一个整体在右侧,在位置 52...71?
  • @DizietAsahi 将每个时间步长并排放置。我在纯 matplotlib 中设法解决了一个问题,但仍然想知道是否有一种聪明的方法可以做到这一点。

标签: python matplotlib seaborn


【解决方案1】:

如果您想在箱线图中使用不同时间序列的色调嵌套,您可以执行以下操作。

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

n = 480
ts0 = pd.Series(np.random.randn(n), index=pd.date_range(start="2014-02-01", periods=n, freq="H"))
ts1 = pd.Series(np.random.randn(n), index=pd.date_range(start="2014-02-01", periods=n, freq="H"))
ts2 = pd.Series(np.random.randn(n), index=pd.date_range(start="2014-02-01", periods=n, freq="H"))

def ts_boxplot(ax, list_of_ts):
    new_list_of_ts = []
    for i, ts in enumerate(list_of_ts):
        ts = ts.to_frame(name='ts_variable')
        ts['ts_number'] = i
        ts['doy']=ts.index.dayofyear
        new_list_of_ts.append(ts)
    plot_data = pd.concat(new_list_of_ts)
    sns.boxplot(data=plot_data, x='doy', y='ts_variable', hue='ts_number', ax=ax)
    return ax

fig, ax = plt.subplots(figsize=(12,5))
ax = ts_boxplot(ax, [ts0, ts1, ts2])

【讨论】:

    猜你喜欢
    • 2019-10-08
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2020-12-31
    • 2016-06-12
    • 2021-06-24
    相关资源
    最近更新 更多