【问题标题】:Plot histogram for data from .txt file with names on x-axis and number on y axis绘制来自 .txt 文件的数据的直方图,其中 x 轴上的名称和 y 轴上的数字
【发布时间】: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


【解决方案1】:

在 Mr.JohanC 的帮助下,我找到了问题的答案。

这是最终程序

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-29
    • 2021-07-24
    • 2014-09-15
    • 2013-04-16
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多