Построение графиков с использованием Matplotlib Python - PullRequest
0 голосов
/ 23 марта 2020

Я хочу напечатать график на разных рисунках, но все графики перекрываются. Здесь у меня есть код для l oop (третий для l oop) в моем коде, и я получаю доступ к позиции numpyArraysDisplay.size и в x подсчета размеров магазинов.

Теперь первая строка отсчитывается от 0 to 44, а затем - вторая строка и т. Д. (Размер не фиксирован).

После этого я добавляю x в список с именем position и построение графика, но для первой строки он отлично сохраняет фигуру графика, но для второй строки он перекрывается с первой на том же рисунке и т. д.

Но я хочу, чтобы все графики на разных рисунках для всей линии , Я отобразил рисунок с перекрывающимися графиками.

Я написал ниже код:

import numpy as np
import csv
from scipy.stats import entropy
from matplotlib import pyplot as plt

position = []
store_entropy = []  # Empty list defined to store the list of entropy
outputfile = open("Output.txt", "w")  # Output file open in write mode for saving the outputs

# Reading the csv file by reader
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for line in reader:
        lines = filter(None, line[2:])
        lines1 = ' '.join(lines).split(',')

        # Loop for every rows in the file
        for row in lines1[::]:
            makeOneLine = row.rstrip('\n')
            delimiter = " "
            makeOneLine = delimiter.join(makeOneLine.split(delimiter, 3))
            # Makes Numpy Array of all the lines in the file
            numpyArraysDisplay = np.array(list(makeOneLine.split(" ")))
            # print(numpyArraysDisplay)
            outputfile.write(str(numpyArraysDisplay) + '\n')

            # Loop for defining the first segment of the the Numpy Arrays
            for x in range(numpyArraysDisplay.size):
                part1 = numpyArraysDisplay[:x + 1]  # First segment divide
                strings, counts = np.unique(part1, return_counts=True)
                # Counting the frequency of the words appearing in the file line by line
                CountWordsfrequency = np.array(list(dict(zip(strings, counts)).values()))
                # print(CountWordsfrequency)
                outputfile.write(str(CountWordsfrequency) + '\n')

                # Loop for finding the Probability and Entropy of the dialogue types
                for y in range(0, CountWordsfrequency.size):
                    probability = CountWordsfrequency[y] / part1.size
                    outputfile.write("Probability is : " + str(probability) + '\n')
                ent2 = entropy(counts, base=10)
                outputfile.write("Entropy is \t" + str(ent2) + '\n')
                # Store all the Entropies in a list for further work
                store_entropy.append(ent2)
            # print(store_entropy)
                position.append(x+1)
            print(position)
            plt.figure(figsize=(15, 7))
            plt.plot(position, store_entropy, '-o')
            plt.xlabel("Segmentation Break Point")
            plt.ylabel("Entropy")
            plt.xticks(np.arange(0, len(position) + 1, 1))
            plt.savefig('Plots/', figurewidth='25cm')
            plt.show()
            plt.clf()
size = len(store_entropy)
# One Line for loop and if condition to slipt the list by particular values as
# we have to give list inside list for passing particular index of entropy
idx_list = [idx for idx, val in enumerate(store_entropy) if val == 0.0]
res = [store_entropy[i: j] for i, j in zip([0] + idx_list, idx_list + ([size] if idx_list[-1] != 
size else []))]
# print(res)
# for loop and if condition for setting the lists of the Entropies index starting
# from zero instead of 1 and removing the empty lists created in the lists.
res2 = [x for x in res if x != []]
#print(res2)
# print("The List after Split:" + str(res))
#print(res2[0])

Вывод выглядит так: Overlapped image of graph

Но я хочу, чтобы все графики на разных рисунках.

1 Ответ

0 голосов
/ 23 марта 2020

В этом вышеупомянутом случае, когда я просмотрел свой код, я обнаружил, что если я хочу передать списки на plt.plot(), то возможно, что мы просто передадим переменную списка. Он автоматически c принимает индекс и значения, когда мы строим графики, используя циклы for.

У меня есть решение ниже и достигается результат.

for a, b in enumerate(res2):
    plt.figure(figsize=(15, 7))
    plt.plot(b, '-*', color="red")
    plt.xlabel("Dialogue Act Types")
    plt.ylabel("Entropy")
    plt.xticks(np.arange(0, len(b) + 1, 1))
    plt.savefig('Plots/', figurewidth='25cm')
    plt.show()
    plt.close()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...