Friday, February 24, 2012

Plots with several histograms

Creating a plot with two histograms

Here is a method that you can use to plot two histograms in the same figure sharing the same X-axis, keeping some distance between the histograms:

 def twohists(x1,x2,xmin,xmax,x1leg='$x_1$',x2leg='$x_2$',xlabel='',sharey=False):  
      """  
 Script that plots two histograms of quantities x1 and x2.   
   
 Arguments:  
 - x1,x2: arrays with data to be plotted  
 - xmin,xmax: lower and upper range of plotted values, will be used to set a consistent x-range  
      for both histograms.  
 - x1leg, x2leg: legends for each histogram       
 - xlabel: self-explanatory.  
   
 Inspired by http://www.scipy.org/Cookbook/Matplotlib/Multiple_Subplots_with_One_Axis_Label.  
   
 Rodrigo Nemmen  
 v1 Dec. 2011  
 v1.1 Feb. 2012: Added sharey argument.  
      """  
   
      pylab.clf()  
      pylab.rcParams.update({'font.size': 15})  
      fig=pylab.figure()  
        
      a=fig.add_subplot(2,1,1)  
      if sharey==True:  
           b=fig.add_subplot(2,1,2, sharex=a, sharey=a)  
      else:  
           b=fig.add_subplot(2,1,2, sharex=a)  
        
      a.hist(x1,label=x1leg,color='b')  
      a.legend(loc='best',frameon=False)  
      a.set_xlim(xmin,xmax)  
        
      b.hist(x2,label=x2leg,color='r')  
      b.legend(loc='best',frameon=False)  
        
      pylab.setp(a.get_xticklabels(), visible=False)  
   
      b.set_xlabel(xlabel)  
      b.set_ylabel('Number',verticalalignment='bottom')  
      pylab.minorticks_on()  
      pylab.subplots_adjust(hspace=0.15)  
      pylab.draw()  

... and here is a example script that uses the method above:

 """  
 Illustrates how to use the twohists method.  
 """  
 import nemmen  
 import scipy, pylab  
   
 # Generates a normal distribution  
 x1=scipy.random.standard_normal(100)  
   
 # Generates a uniform random distribution  
 x2=scipy.random.uniform(-3,3,100)  
   
 nemmen.twohists(x1,x2,-3,3,'Normal','Uniform')  
   
 pylab.show()  

... to create the following plot:



Creating a plot with three histograms


I also wrote a recipe that makes a plot with three histograms:

 def threehists(x1,x2,x3,xmin,xmax,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',xlabel='',sharey=False):  
      """  
 Script that plots three histograms of quantities x1, x2 and x3.   
   
 Arguments:  
 - x1,x2,x3: arrays with data to be plotted  
 - xmin,xmax: lower and upper range of plotted values, will be used to set a consistent x-range  
      for both histograms.  
 - x1leg, x2leg, x3leg: legends for each histogram       
 - xlabel: self-explanatory.  
 - sharey: sharing the Y-axis among the histograms?  
   
 Example:  
 x1=Lbol(AD), x2=Lbol(JD), x3=Lbol(EHF10)  
 >>> threehists(x1,x2,x3,38,44,'AD','JD','EHF10','$\log L_{\\rm bol}$ (erg s$^{-1}$)',sharey=True)  
   
 Inspired by http://www.scipy.org/Cookbook/Matplotlib/Multiple_Subplots_with_One_Axis_Label.  
   
 Rodrigo Nemmen  
 v1 Dec. 2011  
 v1.1 Feb. 2012:     Added sharey keyword.  
      """  
   
      pylab.clf()  
      pylab.rcParams.update({'font.size': 15})  
      fig=pylab.figure()  
        
      a=fig.add_subplot(3,1,1)  
      if sharey==True:  
           b=fig.add_subplot(3,1,2, sharex=a, sharey=a)  
           c=fig.add_subplot(3,1,3, sharex=a, sharey=a)  
      else:  
           b=fig.add_subplot(3,1,2, sharex=a)  
           c=fig.add_subplot(3,1,3, sharex=a)            
        
      a.hist(x1,label=x1leg,color='b')  
      a.legend(loc='best',frameon=False)  
      a.set_xlim(xmin,xmax)  
        
      b.hist(x2,label=x2leg,color='r')  
      b.legend(loc='best',frameon=False)  
   
      c.hist(x3,label=x3leg,color='y')  
      c.legend(loc='best',frameon=False)  
        
      pylab.setp(a.get_xticklabels(), visible=False)  
      pylab.setp(b.get_xticklabels(), visible=False)  
   
      c.set_xlabel(xlabel)  
      b.set_ylabel('Number')  
      pylab.minorticks_on()  
      pylab.subplots_adjust(hspace=0.15)  
      pylab.draw()  

... and as before, here is a script that illustrates how to use the above method:

 """  
 Illustrates how to use the threehists method.  
 """  
 import nemmen  
 import scipy, pylab  
   
 # Generates a normal distribution  
 x1=scipy.random.standard_normal(100)  
   
 # Generates a uniform random distribution  
 x2=scipy.random.uniform(-3,3,100)  
   
 x3=scipy.random.standard_normal(1000)  
   
 nemmen.threehists(x1,x2,x3,-3,3,'Normal ($n=100$)','Uniform','Normal ($n=1000$)')  
   
 pylab.show()  

... creating this plot:



39 comments:

  1. Nice explanation, using this for my science fair project

    ReplyDelete
  2. Well described about a plot creating, you have amazing skills,I am here to discuss a simple definition as-A histogram is a graphical representation of frequency distribution by using vertical bars whose widths represent class intervals and areas are proportional to the corresponding frequencies.
    How to Graph a Circle

    ReplyDelete
  3. Hello Admin,
    I really enjoyed while reading your article, the information you have mentioned in this post was damn good. Keep sharing your blog with updated and useful information.
    Regards,
    R Programming Training in Bangalore

    ReplyDelete
  4. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Data Science with R Programming training in Electronic City

    ReplyDelete
  5. I read this article. I think You have put a lot of effort to create this article. I appreciate your work.
    Thank you much more for sharing with us...!
    Reactjs Training in Chennai |
    Best Reactjs Training Institute in Chennai |
    Reactjs course in Chennai

    ReplyDelete
  6. I feel really happy to have seen your webpage and look forward to so
    many more entertaining times reading here. Thanks once more for all
    the details.
    I feel really happy to have seen your webpage and look forward to so
    many more entertaining times reading here. Thanks once more for all
    the details.

    ReplyDelete
  7. Very Informative blog thank you for sharing. Keep sharing.

    Best software training institute in Chennai. Make your career development the best by learning software courses.

    best php training in chennai
    best msbi training institute in chennai
    rpa training in chennai

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Thanks for sharing! Very helpful and well explained.
    tableau certification

    ReplyDelete
  10. Thanks for sharing such a thoughtful and informative blog post. I truly appreciate the clarity and engaging style you used to explain the topic. It’s not often that I come across content that is both easy to follow and highly insightful. Looking forward to reading more of your work!
    Microsoft Azure Certification Course

    ReplyDelete
  11. Building data science skills requires more than theoretical knowledge. Freshers need practical exposure to understand how data science tools and technologies work in real-world situations. Real-time projects help beginners gain experience in data collection, data cleaning, exploratory data analysis, and machine learning. These activities also improve critical thinking and prepare students to handle industry-related challenges.

    A professional Data Scientist Course in Chennai provides opportunities to develop these skills through hands-on learning and practical projects. By applying their knowledge to real-time scenarios, freshers can build technical confidence, improve their project experience, and take meaningful steps toward a data science career.

    ReplyDelete
  12. Digital finance is transforming the way businesses manage accounting, financial reporting, budgeting, and business operations. SAP FICO skills help professionals understand modern financial processes, improve reporting accuracy, and manage financial data efficiently. Learning SAP FICO also helps freshers and working professionals develop practical knowledge of financial management systems and adapt to changing industry requirements.

    Choosing the Best SAP FICO Training Institute in Chennai can help aspiring professionals build strong ERP knowledge through practical training and real-time project experience. With proper guidance and hands-on learning, candidates can improve their SAP FICO skills, strengthen their career opportunities, and prepare for growing roles in digital finance and enterprise financial management.

    ReplyDelete
  13. Bridging the gap between programming theory and practical implementation is essential for becoming a successful Python Full Stack Developer. Students need opportunities to work with different technologies and understand how complete web applications are developed. Learning Python programming, front-end development, back-end frameworks, and database management through practical exercises helps learners gain a better understanding of application development.

    A Python Full Stack Developer Course in Chennai provides aspiring developers with opportunities to strengthen their technical abilities through hands-on learning. Working on real-time projects helps students understand application workflows, identify coding errors, and develop effective solutions. These practical experiences can improve their confidence and prepare them for entry-level development roles.

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. SAP Sales and Distribution (SD) is an essential SAP module that helps organizations manage sales activities, streamline order processing, and improve customer service. It supports important business operations such as sales order creation, customer data management, pricing, delivery processing, billing, shipping, and order fulfillment. Enrolling in SAP SD Training in Chennai can help learners understand sales and distribution processes, develop functional knowledge, and explore career opportunities in sales operations and SAP consulting.

    ReplyDelete