在Python中使用导出的数据绘制累积直方图

时间:2020-05-31 18:56:37

标签: python matplotlib cumulative-frequency

我正在尝试绘制类似于以下所示的累积直方图。它显示了从单词0到92,633表示的文本语料库(x轴)中法语代词“ vous”的出现次数(y轴)。它是使用名为enter image description here的语料库分析应用程序创建的。但是,TXM的图不适合我的出版商的特定要求。我想生成自己的图,将数据导出到python。问题是TXM导出的数据有点令人费解,我想知道如何将其用于绘制图: 这是一个包含整数的一栏txt文件。

其中每个指示文本语料库中“ vous”的位置。单词2620是一个“ vous”, 3376,另外一个,等等。我对Matplotlib的尝试之一:

from matplotlib import pyplot as plt

pos = [2620,3367,3756,4522,4546,9914,9972,9979,9987,10013,10047,10087,10114,13635,13645,13646,13758,13771,13783,13796,23410,23420,28179,28265,28274,28297,28344,34579,34590,34612,40280,40449,40570,40932,40938,40969,40983,41006,41040,41069,41096,41120,41214,41474,41478,42524,42533,42534,45569,45587,45598,56450,57574,57587]
plt.bar(pos, 1)
plt.show()

但这还差得远。 我应该遵循什么步骤来完成绘图?

期望的情节:

desired plot

1 个答案:

答案 0 :(得分:0)

使用matplotlib,您可以按照以下步骤创建阶梯图。 where='post'表示该值在每个x位置都会更改,并保持不变,直到下一个x位置为止。 x值是文本中的位置,前缀为零以使图形以出现的零个开始。文本长度附加在末尾。 y值是数字0, 1, 2, ...,其中重复最后一个值以完全绘制最后一步。

from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator, StrMethodFormatter
import numpy as np

pos = [2620,3367,3756,4522,4546,9914,9972,9979,9987,10013,10047,10087,10114,13635,13645,13646,13758,13771,13783,13796,23410,23420,28179,28265,28274,28297,28344,34579,34590,34612,40280,40449,40570,40932,40938,40969,40983,41006,41040,41069,41096,41120,41214,41474,41478,42524,42533,42534,45569,45587,45598,56450,57574,57587]
text_len = 92633
cum = np.arange(0, len(pos) + 1)
fig, ax = plt.subplots(figsize=(12, 3))
ax.step([0] + pos + [text_len], np.pad(cum, (0, 1), 'edge'), where='post', label=f'vous {len(pos)}')
ax.xaxis.set_major_locator(MultipleLocator(5000)) # x-ticks every 5000
ax.xaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # use the thousands separator
ax.yaxis.set_major_locator(MultipleLocator(5)) # have a y-tick every 5
ax.grid(b=True, ls=':') # show a grid with dotted lines
ax.autoscale(enable=True, axis='x', tight=True) # disable padding x-direction
ax.set_xlabel(f'T={text_len:,d}')
ax.set_ylabel('Occurrences')
ax.set_title("Progression of 'vous' in TCN")
plt.legend() # add a legend (uses the label of ax.step)
plt.tight_layout()
plt.show()

example plot

相关问题