Home > Mobile >  Plot two legends of own calculated values
Plot two legends of own calculated values

Time:10-11

I have a problem. I want to show mean and median inside my plot. But unfortunately it overwrites it (see the second code snippet). When I do plt.legend([...,...] the output is not what I want. How can I show the mean and median as linie and plot the legend of them both with the correct color and linestyle?

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

#d = {'distance_km': [1, 100, 12, 14],}
d = {'distance_km': random.randint(100, size=(20)),}
df_calculation = pd.DataFrame(data=d)

sns.set_style("white")
# Calculation of meand and median
mean=df_calculation["distance_km"].mean()
median = df_calculation["distance_km"].median()

plt.figure(figsize=(11,5))
ax = sns.distplot(df_calculation["distance_km"],color='lightblue')
ax.axvline(mean, color='r', linestyle='--')
ax.axvline(median, color='green', linestyle='--')
plt.legend([{f'Mean = {round(df_calculation["distance_km"].mean(), 2)}':mean}, {f'Median = {round(df_calculation["distance_km"].mean(), 2)}':median}])

plt.box(False)
plt.xlabel("\n Km", fontsize = 12)
plt.ylabel("", fontsize = 12)
plt.show()

enter image description here

Here it works bot it would be overwritten but the color is not correct

#Plotting Distribution Drugs Numbers per Condition
#plt.style.use('seaborn-whitegrid')
mean=df_calculation["distance_km"].mean()
median = df_calculation["distance_km"].median()
plt.figure(figsize=(11,5))
sns.set_style("white")
ax = sns.distplot(df_calculation["distance_km"],color='lightblue')
ax.axvline(mean, color='r', linestyle='--')
plt.legend({f'Mean = {round(df_calculation["distance_km"].mean(), 2)}':mean})
ax.axvline(median, color='green', linestyle='--')
plt.legend({f'Median = {round(df_calculation["distance_km"].median(), 2)}':median})
plt.box(False)
plt.xlabel("\n Kilometer", fontsize = 12)
plt.ylabel("", fontsize = 12)
plt.show()

enter image description here

CodePudding user response:

Use the label parameter inside plot with legend

  • Related