使用 matplotlib、FITTED-LINE 构建 Zipf 分布

Constructing Zipf Distribution with matplotlib, FITTED-LINE

我有一个段落列表,我想在其中运行对其组合进行 zipf 分布。

我的代码如下:

from itertools import *
from pylab import *
from collections import Counter
import matplotlib.pyplot as plt


paragraphs = " ".join(targeted_paragraphs)
for paragraph in paragraphs:
   frequency = Counter(paragraph.split())
counts = array(frequency.values())
tokens = frequency.keys()

ranks = arange(1, len(counts)+1)
indices = argsort(-counts)
frequencies = counts[indices]
loglog(ranks, frequencies, marker=".")
title("Zipf plot for Combined Article Paragraphs")
xlabel("Frequency Rank of Token")
ylabel("Absolute Frequency of Token")
grid(True)
for n in list(logspace(-0.5, log10(len(counts)-1), 20).astype(int)):
    dummy = text(ranks[n], frequencies[n], " " + tokens[indices[n]],
    verticalalignment="bottom",
    horizontalalignment="left")

PURPOSE 我试图在这张图中绘制 "a fitted line",并将其值赋给一个变量。但是我不知道如何添加。对于这两个问题,我们将不胜感激。

我知道自问这个问题以来已经有一段时间了。但是,我在 scipy site.
找到了这个问题的可能解决方案 我想我会 post 在这里,以防其他人需要。

我没有段落信息,所以这里是一个名为 frequencydict,它的值是段落出现次数。

然后我们获取它的值并转换为 numpy 数组。定义 zipf distribution parameter 必须 >1.

最后显示样本的直方图,以及概率密度函数

工作代码:

import random
import matplotlib.pyplot as plt
from scipy import special
import numpy as np

#Generate sample dict with random value to simulate paragraph data
frequency = {}
for i,j in enumerate(range(50)):
    frequency[i]=random.randint(1,50)

counts = frequency.values()
tokens = frequency.keys()


#Convert counts of values to numpy array
s = np.array(counts)

#define zipf distribution parameter. Has to be >1
a = 2. 

# Display the histogram of the samples,
#along with the probability density function
count, bins, ignored = plt.hist(s, 50, normed=True)
plt.title("Zipf plot for Combined Article Paragraphs")
x = np.arange(1., 50.)
plt.xlabel("Frequency Rank of Token")
y = x**(-a) / special.zetac(a)
plt.ylabel("Absolute Frequency of Token")
plt.plot(x, y/max(y), linewidth=2, color='r')
plt.show()

情节