[英]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.这是我第一次尝试 plot x 轴上的名称直方图。 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保存在.txt文件中的数据
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.不知道我哪里出错了。
With the help of inputs from Mr.JohanC, I have found the answer to the question posted.在 Mr.JohanC 的帮助下,我找到了问题的答案。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.