【问题标题】:Plot boxplot and line from pandas绘制熊猫的箱线图和线条
【发布时间】:2018-10-15 08:35:52
【问题描述】:

我正在尝试重现此图 - 每个点都有一个箱线图的线图:

Imgur

但是,线图总是从原点开始,而不是从第一个 x 刻度开始:

Imgur

我已将我的数据结构收集在一个 pandas 文件中,每个列标题是 k_e(x 轴的),该列是所有数据点。

我正在绘制每列的平均值和箱线图,如下所示:

df = df.astype(float)

_, ax = plt.subplots()
df.mean().plot(ax = ax)
df.boxplot(showfliers=False, ax=ax)

plt.xlabel(r'$k_{e}$')
plt.ylabel('Test error rate')
plt.title(r'Accuracies with different $k_{e}$')

plt.show()

我参考了下面的链接,因此我通过了“斧头”位置,但这没有帮助。

plot line over boxplot using pandas DateFrame

编辑:这是一个最小的例子:

test_errors_dict = dict() np.random.seed(40)

test_errors_dict[2] = np.random.rand(20)
test_errors_dict[3] = np.random.rand(20)
test_errors_dict[5] = np.random.rand(20)

df = pd.DataFrame(data=test_errors_dict)
df = df.astype(float)

_, ax = plt.subplots()
df.mean().plot(ax=ax)
df.boxplot(showfliers=False, ax=ax)

plt.show()

结果: Imgur

如上图,线图与箱线图不对齐

【问题讨论】:

标签: python pandas matplotlib visualization


【解决方案1】:

方框位于位置 1,2,3,而绘图位于位置 2,3,5。您可以重新索引mean 系列以同时使用位置 1、2、3。

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

test_errors_dict = dict()
np.random.seed(40)

test_errors_dict[2] = np.random.rand(20)
test_errors_dict[3] = np.random.rand(20)
test_errors_dict[5] = np.random.rand(20)

df = pd.DataFrame(data=test_errors_dict)
df = df.astype(float)

mean = df.mean()
mean.index = np.arange(1,len(mean)+1)

_, ax = plt.subplots()
mean.plot(ax=ax)
df.boxplot(showfliers=False, ax=ax)

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-16
    • 2018-10-20
    • 2021-06-16
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    相关资源
    最近更新 更多