繁体   English   中英

同一张图上的多个箱线图

[英]Multiple boxplots on the same graph

我需要在同一张图上创建多个箱线图。 运动是 3。我需要在每项运动的同一张图上获得 3 个箱线图,在 y 轴上有一个特定的变量。 我需要能够更改变量。 每个学生的变量被多次注册,并由 3 个最大数字的平均值给出。 我有 30 名学生用 ID 标识(从 1 到 30)。 每个学生只做一项运动。 这是我写的,但显然它不起作用。 有人可以帮忙吗? 我希望我的解释是有道理的。

def boxplot(sport, variable):
    list=[]
    for l in range(1,31):
        g = df[(df.ID == l) & (df.sport == sport)][variable].nlargest(n=3).mean()
        list.append(g)
    my_dict = {f'Boxplot for {variable} in {sport}': list}
    fig, ax = plt.subplots()
    ax.boxplot(my_dict.values())
    ax.set_xticklabels(my_dict.keys())
    plt.show()

这是一种方法。

import plotly.express as px

df = px.data.tips()

fig = px.box(df, x="day", y="total_bill", color="smoker")
fig.update_traces(quartilemethod="exclusive") # or "inclusive", or "linear" by default
fig.show()

在此处输入图像描述

如果您的数据没有融化或堆叠,您可以像这样更改布局。

https://pandas.pydata.org/docs/reference/api/pandas.melt.html

最后,对于Matplotlib,你可以这样做。

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

# Results of the long jump finals at two Olympic Games
data = pd.DataFrame({
    'London 2012 (Men)': [8.31, 8.16, 8.12, 8.11, 8.10, 8.07, 8.01, 7.93],
    'Rio 2016 (Men)': [8.38, 8.37, 8.29, 8.25, 8.17, 8.10, 8.06, 8.05],
    'London 2012 (Women)': [7.12, 7.07, 6.89, 6.88, 6.77, 6.76, 6.72, 6.67],
    'Rio 2016 (Women)': [7.17, 7.15, 7.08, 6.95, 6.81, 6.79, 6.74, 6.69]
})

# Plot
bp = plt.boxplot(
    # A data frame needs to be converted to an array before it can be plotted this way
    np.array(data),
    # You can use the column headings from the data frame as labels
    labels=list(data)
)
# Axis details
plt.title('Long Jump Finals')
plt.ylabel('Distance [m]')
plt.xlabel('Olympics')
plt.minorticks_on()
plt.tick_params(axis='x', which='minor', bottom=False)
plt.tick_params(axis='x', which='major', labelsize='small')

plt.show()

在此处输入图像描述

这是最后一次更新。 确保 y 轴是数字...

import pandas as pd
import plotly.express as px
import matplotlib.pyplot as plot

df = px.data.tips()
df=pd.DataFrame(df)
print(type(df))
df.head()
df.columns = ['total_bill', 'tip', 'sex', 'smoker', 'day', 'time', 'size']

b_plot = df.boxplot(column = ['tip','size','total_bill']) 
b_plot.plot()
plot.show()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM