How to plot a histogram using Matplotlib in Python with a list of data?

前端 未结 5 785
醉梦人生
醉梦人生 2020-12-04 09:06

I am trying to plot a histogram using the matplotlib.hist() function but I am not sure how to do it.

I have a list

probability = [0.360         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 09:35

    If you want a histogram, you don't need to attach any 'names' to x-values, as on x-axis you would have data bins:

    import matplotlib.pyplot as plt
    import numpy as np
    %matplotlib inline
    np.random.seed(42)
    x = np.random.normal(size=1000)
    plt.hist(x, density=True, bins=30)  # `density=False` would make counts
    plt.ylabel('Probability')
    plt.xlabel('Data');
    

    You can make your histogram a bit fancier with PDF line, titles, and legend:

    import scipy.stats as st
    plt.hist(x, density=True, bins=30, label="Data")
    mn, mx = plt.xlim()
    plt.xlim(mn, mx)
    kde_xs = np.linspace(mn, mx, 301)
    kde = st.gaussian_kde(x)
    plt.plot(kde_xs, kde.pdf(kde_xs), label="PDF")
    plt.legend(loc="upper left")
    plt.ylabel('Probability')
    plt.xlabel('Data')
    plt.title("Histogram");
    

    However, if you have limited number of data points, like in OP, a bar plot would make more sense to represent your data (then you may attach labels to x-axis):

    x = np.arange(3)
    plt.bar(x, height=[1,2,3])
    plt.xticks(x, ['a','b','c'])
    

提交回复
热议问题