Python matplotlib 格式

问题描述

我的 Python 程序正在生成一个相互堆叠的图形。如果matplotlib散点图已经相互堆叠,我想自动使用下一页

from matplotlib import pyplot as plt


def countWords(file):
    plt.style.use("seaborn")
    x = []
    y = []
    words = {}
    i = 0
    for line in file:
        w = line.split(" ")  # output list
        for b in line.split():
            words[b] = words.get(b,0) + 1

        for w,c in words.items():
            plt.scatter(w,c,cmap="Greens",edgecolors="black",alpha=0.75,linewidths=1)
    plt.locator_params(axis="both",integer=True,tight=False)
    plt.xlabel("Words")
    plt.ylabel("Number of Occurrence")
    
    plt.show()


file = open("mytext.txt","r")
print(countWords(file))

This is the sample image

mytext.txt

解决方法

要减少 x 轴上的字数,您可以拆分 words dict 并创建多个图形/图表并将它们保存在本地。这些图像可以通过 Microsoft Word 或 LibreOffice 导入以创建页面。您也可以 rotate 它们以节省空间。可以更改图形和文本大小。

另外,为什么需要散点图?有(堆叠/分组)条形图(参见https://matplotlib.org/stable/gallery/index.html#)。

我建议使用 with 语句打开文件(请参阅 https://thispointer.com/python-open-a-file-using-open-with-statement-benefits-explained-with-examples/)。