У меня есть программа, которая работает нормально и строит графики из предоставленного файла данных. Программа открывает CSV-файл, фильтрует данные в столбце 5 для уникальных значений и записывает CSV-файл для каждого уникального значения, сопровождаемый данными из исходного файла, и я строю график для сравнения различных значений в каждом столбце. Поэтому для этого примера у меня должно быть 3 уникальных значения в столбце 5, который создает 3 уникальных CSV-файла с префиксом синий, зеленый и красный. Затем я строю график, скажем, столбец 2 для каждого сине-зеленого и красного файла и сравниваю на графике - поэтому я пробежусь по всем столбцам в синем, зеленом, красном CSV-файлах и сравню их на графике.
Я бы нравится держать предыдущий график открытым при просмотре следующего графика вместо того, чтобы закрывать окно графика. Я пытался использовать plt.figure (), но одновременно открывал три диаграммы - извиняюсь за плохое программирование. Я только начал учиться Python. Спасибо за любую помощь / совет.
Начиная с строки 40 в программе есть код печати, который у меня был проблемы с
from matplotlib import style
from matplotlib import pyplot as plt
import numpy as np
import csv
# import random used for changing line colors in chart
import random
from itertools import cycle
# opens a the input file and reads in the data
with open('Test_colours_in.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
# prints list of unique values in column 5 of csv of input file
my_list = set()
for line in csv_reader:
my_list.add(line['Name5'])
print(my_list)
# takes these unique values and creates files associated with each unique value
for item in my_list:
with open(item + '_'+'Test.csv', 'w', newline='') as new_file:
fieldnames = ['Name1', 'Name2', 'Name3', 'Name4', 'Name5', 'Name6', 'Name7', 'Name8']
csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames)
csv_writer.writeheader()
# filters the original file for each item in the list of unique values and writes them to respective file
csv_file.seek(0) # Reposition to front of file
filtered = filter(lambda r: r['Name5'] == item, csv_reader)
for row in filtered:
csv_writer.writerow(row)
# Section of code below plots data from each of the filtered files
# reads in columns 1 for time (x) and 3,4 for y1 and y2
# to test for data type in column 0,1,2
# loops up to 3 (not including 3 )
#
# list of color for plots https://matplotlib.org/3.1.0/gallery/color/named_colors.html
# color values choice below
# b , g, r, c, m, y, tab:blue, tab:orange, tab:purple, tab:gray
#
# this is the bit of code I am have trouble with I need to run through a list of columns and
# have previous plots visible when a look at the next graph. At the moment I have just picked the first
# three column and loop through these
for i in range(3):
# apples, pears and oranges really Name1,Name2 and Name3 will change these later
user_input = input('enter Name1, Name2 or Name3, q to quit ?')
sample_string = user_input
if sample_string[:1] == 'q':
break
if sample_string == 'Name1':
user = int(0)
if sample_string == 'Name2':
user = int(1)
if sample_string == 'Name3':
user = int(2)
for item in my_list:
print(user)
# Chooses a random number between 1 and 16777215
random_number = random.randint(1, 16777215)
# convert the random number to a hex number then to string
hex_number = str(hex(random_number))
# [2;] removes the 0x from the hexadecimal and add #
hex_number = '#' + hex_number[2:]
print(random_number)
x, y = np.loadtxt(item + '_'+'Test.csv', skiprows=1, usecols=[0, user], unpack=True, delimiter=',')
plt.plot(x, y, hex_number, label=item, linewidth=5)
style.use('ggplot')
plt.title('Data v Time')
plt.ylabel('Data')
plt.xlabel('Time seconds')
plt.legend()
plt.grid(True, color='k')
plt.show()
CSV-файл ниже
Имя1, Имя2, Имя3, Имя4, Имя5, Имя6, Имя7, Имя8 1,2,3 4, Красный, 6,7,8 2,5,6,7, Синий, 6,7,8 3,5,7,7, Синий, 6,7,8 4,5,8,7, Синий, 6,7,8 5,2,4,4, Красный, 6,7,8 6,2,5,4, Красный, 6,7,8 7,8,10,10, Зеленый, 6,7,8 8,8,11,10, Зеленый, 6,7,8 9,8,12,10, Зеленый, 6,7,8