-1

I want to compute and display a histogram and also plotting the mean, variance and quartiles. I have no idea how to do this. Coding isn't my strength and plotting stuff is the worst.

I calculated the probabilities, mean, var, quartiles. I also plotted the probabilities and the pdf curve, which was simple with seaborn (this helped me out a bit).

Is this actually correct so far and how do I add mean, var and quartiles to the plot?

import seaborn as sns
import numpy as np
import math
import statistics

# calculating probabilities
i = 1
probability = []
for i in range(100):
    probability.append((61/99) * math.e**(-0.5 * i) + (38/99) * math.e**(-0.25 * i))

mean = sum(probability)/float(len(probability))
variance = statistics.variance(probability)
q25 = np.quantile(probability, 0.25)
q50 = np.quantile(probability, 0.5)
q75 = np.quantile(probability, 0.75)

sns.displot(probability, bins=100, kde=True);

Thanks in advance :)

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Stefan
  • 27
  • 7

1 Answers1

1
  • using plotly you can construct histogram for frequency
  • add lines on a second yaxis for variance, mean, q25, q50, q75
import numpy as np
import math
import statistics
import pandas as pd
import plotly.express as px


# calculating probabilities
i = 1
probability = []
for i in range(100):
    probability.append(
        (61 / 99) * math.e ** (-0.5 * i) + (38 / 99) * math.e ** (-0.25 * i)
    )

mean = sum(probability) / float(len(probability))
variance = statistics.variance(probability)
q25 = np.quantile(probability, 0.25)
q50 = np.quantile(probability, 0.5)
q75 = np.quantile(probability, 0.75)

fig = px.histogram(probability, nbins=100).update_traces(name="frequency")

fig.add_traces(
    px.line(
        pd.DataFrame(index=np.linspace(0, 1, 100)).assign(
            mean=mean, variance=variance, q25=q25, q50=q50, q75=q75
        )
    )
    .update_traces(yaxis="y2")
    .data
).update_layout(
    yaxis2={"side": "right", "anchor": "x", "overlaying": "y"},
    legend=dict(
        orientation="h", yanchor="bottom", y=1.02, xanchor="right", title_text="", x=1
    ),
)

fig.show()

enter image description here

Rob Raymond
  • 29,118
  • 3
  • 14
  • 30
  • This looks great, thanks! Is there a way to add the probability density graph on the histogram? That's something the seaborn line of code did which I liked. – Stefan Oct 17 '21 at 10:55