python - 创建 Pi 数字的直方图

标签 python python-3.x graphing

我在绘制 Pi 前一百万位数字的分布直方图时遇到问题。

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# import pandas as pd

"""
This program charts a histogram of the distribution of the digits in pi.
"""
# Assign variable to the 1 Million digits of Pi
file_object = open('pi_million_digits.txt', 'r')
pi = file_object.read()

# Add the million digits to a list for plotting.
digit_list = []
for digit in pi:
    digit_list.append(digit)

# Plot the histogram
bins = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

plt.hist(digit_list, bins, histtype = 'bar', rwidth = 0.5)

plt.title('Distribution of Digits in Pi')
plt.xlabel('Digits')
plt.ylabel('Times appeared in the first million digits of Pi')

plt.show()

此代码将所有数字转储到一个容器中,但我不知道如何将每个数字分配到其各自的容器中。

此代码还尝试绘制 Pi 中的小数点图形,但我现在不太关心修复该问题。

任何关于清理这个问题和修复图表的帮助都是值得赞赏的。

Here is a link for the first million digits of pi to save as a .txt doc

最佳答案

您的问题是,当您从文件中读取数字时,它们都被视为字符串。您需要做的是将每个数字转换为整数

digit_list.append(int(digit))

-以便根据您提供的 bin 对它们进行分类。

关于python - 创建 Pi 数字的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51352925/

相关文章:

python - 在多个线程中重用 Tensorflow session 导致崩溃

math - 如何反转 Desmos 上的 y 轴?

java - Google App Engine 和 Python 连接项目

gTTS(谷歌文本转语音)模块的Python代码错误

python - 如何使用 tkinter 更新框架?

python - 将包含 "de"、 "da"等的名称拆分为第一个、中间的、最后一个等

python - 逐行处理非常大 (>20GB) 的文本文件

python - 在python中绘制热图

ios - 如何在 iOS 中使用 JBLineChart 绘制和自定义两条线?

r - 如何在 Caret 包中为 kNN 模型创建决策边界图?