Цикл графиков в матплотлиб
Хочу, чтобы в каждом столбце считалось количество единиц, двоек, троек и четверок и отрисовывались графики ОТДЕЛЬНО для каждого столбца.
1 2 1 1 2
1 1 1 0 1
1 0 1 1 1
1 3 1 0 1
1 3 1 1 1
1 1 1 1 1
1 1 1 3 1
Но не догоняю в этой логике матплотлиб с построением новых окон для каждого графика... казалось, что в коде и так это подразумевается. Но в итоге графики сохраняются пустыми на 0 кб
def autolabel(rects, labels=None, height_factor=1.01):
for i, rect in enumerate(rects):
height = rect.get_height()
if labels is not None:
try:
label = labels[i]
except (TypeError, KeyError):
label = ' '
else:
label = '%d' % int(height)
ax.text(rect.get_x() + rect.get_width()/2., height_factor*height,
'{}'.format(label),
ha='center', va='bottom')
for col in df.columns:
arr = df[col]
a = 0
for i in arr[:]:
if i == 1:
a += 1
b = 0
for i in arr[:]:
if i == 2:
b += 1
c = 0
for i in arr[:]:
if i == 3:
c += 1
d = 0
for i in arr[:]:
if i == 4:
d += 1
# counts = df.iloc[0]
resps = ['Вариант 1', 'Вариант 2', 'Вариант 3', 'Вариант 4']
counts = [a, b, c, d]
print(a, b, c, d)
fig, ax = plt.subplots(figsize=(6, 4)) #размеры
patches = plt.bar(resps, counts, edgecolor='pink', width=1.0)
jet = pl.get_cmap('PiYG', len(patches)) #увета
autolabel(ax.patches, height_factor=1.01)
ax.set_title('{}'.format(str(col)), loc='left')
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
#ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
#plt.axis('off')
for i in range(len(patches)):
patches[i].set_facecolor(jet(i))
plt.savefig("C:/Users/Я/{}.png".format(str(col)))
Ответы (1 шт):
Автор решения: Владислав Харламов
→ Ссылка
import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
col_1, col_2, col_3, col_4 = [1, 1, 1, 1, 1, 1, 1], [2, 1, 0, 3, 3, 1, 1], [1, 0, 1, 0, 1, 1, 3], [2, 1, 1, 1, 1, 1, 1]
df = pd.DataFrame({f'col_{index}' : col for index, col in enumerate([col_1, col_2, col_3, col_4])})
for index, column in enumerate(df.columns):
array_counts = Counter(df[column])
x,y = [], []
for key, value in array_counts.items():
x.append(key); y.append(value)
plt.title(f'oX: {x}, oY: {y}')
plt.xlim(-1, 5)
plt.bar(x, y)
plt.savefig(f'pic_{index + 1}.png')