【发布时间】:2021-04-16 12:34:36
【问题描述】:
我是编程新手,我曾尝试为值绘制直方图。这是我第一次尝试在 x 轴上绘制名称的直方图。我浏览了这些帖子,但没有发现任何帮助。我将非常感谢并感谢您的帮助。
.txt 文件中保存的数据
数据
Seyfert1 112
Seyfert2 42
Quasars 131
QuasarsSeyfert1 46
Radiogalaxy 5
BLlacHP 39
Seyfert3 5
HeIIRegions 55
使用的代码如下。
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()
我用同样的方法来绘制带有数字的直方图。不知道我哪里出错了。
【问题讨论】:
-
您可能需要条形图而不是直方图:
plt.bar(x, y) -
嗯,你的第一个问题是
np.loadtxt,它默认只想读取数字。你可以试试x, y = np.loadtxt(f, unpack=True, usecols=[0, 1], dtype=str),然后是y = y.astype(int)。这样x将是一个字符串数组,y将是一个整数数组。 -
它有效,但名称重叠。有没有办法纠正这个问题? '
-
将刻度标签旋转 20 度:
plt.tick_params(axis='x', labelrotation=20) -
这可行,但它切断了 x 轴标签。这意味着我通过使用 plt.tick_params(axis='x', labelrotation=20, labelsize= 8) 减小了每个条的标签大小,但是 x 轴标签被切断
标签: python matplotlib histogram