Search code examples
pythonmatplotlibhistogram

Plot histogram for data from .txt file with names on x-axis and number on y axis


I am new to programming, and I have tried plotting histograms for values. This is the first time I am trying to plot a histogram for names on the x axis. I went through the posts but found none helpful. I will greatly appreciate and be indebted to your help.

The data saved in a .txt file

Data

Seyfert1    112
Seyfert2    42
Quasars     131
QuasarsSeyfert1 46
Radiogalaxy    5
BLlacHP       39
Seyfert3    5
HeIIRegions 55

The code used is given below.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib

f = open('hist.txt','r')
x,y = np.loadtxt(f,unpack=True, usecols=[0,1])
plt.hist(y, bins=10, histtype='bar',facecolor = 'red',  rwidth=1.0)
plt.xlabel('Type of AGN',fontsize=15)
plt.ylabel('Number of galaxies',fontsize=15)
plt.title('Distribution of Type of active galaxies',fontsize=15)
plt.savefig('hist1.pdf',fmt='pdf')
plt.show()

I used the same for plotting the histogram with numbers. Not sure where I am going wrong.


Solution

  • With the help of inputs from Mr.JohanC, I have found the answer to the question posted.

    Here is the final program

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib
    
    
    f = open('hist.txt','r')
    x, y = np.loadtxt(f, unpack=True, usecols=[0, 1], dtype=str)
    y = y.astype(int)
    plt.bar(x, y)
    plt.tick_params(axis='x', labelrotation=10, labelsize= 10)
    plt.xlabel('Type of AGN',fontsize=15)
    plt.ylabel('Number of galaxies',fontsize=15)
    plt.title('Distribution of Type of active galaxies',fontsize=15)
    plt.tight_layout()
    plt.savefig('hist_gal.pdf',fmt='pdf')
    plt.show()