Home > Software engineering >  How to plot errorbars in matplotlib with categorical variables and groups
How to plot errorbars in matplotlib with categorical variables and groups

Time:02-04

I am trying to get the following graphic:

the output

CodePudding user response:

if you are looking to keep the 3 graphs in two rows, you can use add_subplot() and adjust the spacing and the titles as needed. The updated code is given below. Hope this helps...

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

# Define data and parameters
title = "Einzelwertdiagramm mit kategorialen Variablen und Gruppen"
colors = ["#95C13D", "#3B4D18", "#F8AB5D", "#F9B000"]

# Create a sample pandas DataFrame with categorical variables
df = pd.DataFrame({
    'Festzelt': ["Hacker-Festzelt", "Hacker-Festzelt", "Hacker-Festzelt", "Löwenbräu-Festzelt", "Löwenbräu-Festzelt", "Löwenbräu-Festzelt"],
    'Biermenge': [1.068510948, 1.111444388, 1.097928649, 1.097319892, 1.112046892, 1.096458863],
    'Gruppe': ["Abend", "Vormittag", "Nachmittag", "Abend", "Vormittag", "Nachmittag"]
})

# Set the order of the categories in the 'group' column
unique_values = df['Festzelt'].unique()
order = unique_values

# Add grid lines with both horizontal and vertical lines
sns.set_style("whitegrid")

# Compute the standard deviation for each group
grouped = df.groupby("Gruppe")
std = grouped["Biermenge"].std().to_dict()

# Create a list of dictionaries to store the x and y values, as well as the error bars
data = []
for i, group in df.groupby("Gruppe"):
    x = group["Festzelt"].tolist()
    y = group["Biermenge"].tolist()
    y_err = [std[i] for _ in range(len(y))]
    data.append({"x": x, "y": y, "y_err": y_err})

# Create a figure and axes for the plot
fig = plt.figure(figsize=(10, 6)) 

# Plot the data for each group
for i, group in enumerate(data):
    fig.add_subplot(2,2,i 1)
    plt.errorbar(group["x"], group["y"], yerr=group["y_err"], fmt="o", color=colors[i], capsize=10, label=df["Gruppe"].unique()[i])
    plt.gca().title.set_text(df["Gruppe"].unique()[i])

# Add a title and labels to the plot
fig.suptitle(title, fontsize=15)
#plt.xlabel("Festzelt")
#plt.ylabel("Biermenge")
fig.text(0.5, 0.04, 'Festzelt', ha='center', va='center', fontsize=14)
fig.text(0.06, 0.5, 'Biermenge', ha='center', va='center', rotation='vertical', fontsize=14)
fig.subplots_adjust(wspace=.5)

# Show the plot
plt.show()

And the resulting plot is...

enter image description here

  • Related