2

Хочу, чтобы в каждом столбце считалось количество единиц, двоек, троек и четверок и отрисовывались графики ОТДЕЛЬНО для каждого столбца.

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 ответ 1

3
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')
7
  • спасибо, очень изящно и красиво оптимизирует код! Осталось теперь найти решение по несохраняющимся картинкам матплотлиб...
    – Io Io
    18 сен 2020 в 10:56
  • @lo lo, какую ошибку выдает? 18 сен 2020 в 10:58
  • Matplotlib RuntimeWarning exception: Too many figures open simultaneously . plt.clf() не помог
    – Io Io
    18 сен 2020 в 11:01
  • Во всяком случае добавил сохранение в свой код, если все же решите воспользоваться (он работает). 18 сен 2020 в 11:08
  • У меня ваш код работает, кстати. Видим что-то не так с путем, я заменил на эту строчку: plt.savefig("pic_{}.png".format(str(col))) 18 сен 2020 в 11:10

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.