Как отличить определенный цвет столбца x на гистограмме matplotlib? - PullRequest
1 голос
/ 05 апреля 2019

В настоящее время я делаю программу, в которой один из столбцов предназначен для клиента. Я хочу, чтобы этот бар отличался другим цветом. Раньше я делал это путем перебора словаря (barChartObjects), и когда ключ словаря соответствовал аргументу (компании), он менял цвет. Это произошло, так как каждый столбец наносился отдельно и работал отлично. Из-за проблем с форматированием надписей мне пришлось изменить способ отображения графиков, и теперь я озадачен тем, как я могу делать то, что раньше, с моей новой функцией.

def plotCompany(barChartObjects, company):
    # axis of data
    x = []
    y = []
    print("Company: " + company)
    # date for the file output name
    dateForOutput = date.today()
    # append the attributed input to the corresponding axis
    for key, value in barChartObjects.items():
        x.append(key)
        y.append(value)

    freq_series = pd.Series.from_array(y)
    # Plot the figure.
    plt.figure(figsize=(12, 8))

    # this is where I set the color for the graph, I am assuming I will need to change something here
    ax = freq_series.plot(kind='bar', color= "#36C989")

    ax.set_title("Total Shareholder Return (" + (date.today()-timedelta(days=30)).strftime("%b %d %Y") + ")")
    ax.set_xlabel("Companies")
    ax.set_ylabel("Percent Change")
    ax.set_xticklabels(x)

    plt.text(-0.25, 12, "Median: " + str(medianCalc(barChartObjects)) + "%")
    add_value_labels(ax)

    # save the file to my directory.
    plotDirectory = config.getDirectory(company)
    plt.savefig(plotDirectory, quality = 95)

    plt.show()
    return plotDirectory

Выше показано, как настроена моя функция. Для справки ниже приведена предыдущая функция, которую я использовал, которая правильно покрасила их, но имела дурацкое форматирование, поэтому я использовал эту новую функцию.

def graphCompany(barChartObjects, company):
    # axis of data
    x = []
    y = []
    print("Company: " + company)
    # date for the file output name
    dateForOutput = date.today()
    # append the attributed input to the corresponding axis
    for key, value in barChartObjects.items():
        x.append(key)
        y.append(value)

    i = 0

    for key, value in barChartObjects.items():
        if (key == company):
            plt.bar(x[i], y[i],width = calcWidth(barChartObjects), color = "#289EE0")
            i = i + 1
        else:
            plt.bar(x[i], y[i],width = calcWidth(barChartObjects), color = "#36C989")
            i = i + 1

    # label the bar chart
    plt.autoscale(enable=True, axis='both', tight=None)
    plt.xlabel("Companies")
    plt.ylabel("Percent Change")
    plt.title("Total Shareholder Return (" + (date.today()-timedelta(days=30)).strftime("%b %d %Y") + ")")
    plt.text(-0.70, 9.25, "Median: " + str(medianCalc(barChartObjects)) + "%")


    # add labels to see the specific percent change for each x
    for a,b in zip(x, y):
        plt.text(a, b, str("%.2f" % b + "%"))



    # save the file to my directory.
    plotDirectory = config.getDirectory(company)
    plt.savefig(plotDirectory, quality = 95)
    plt.show()
    return plotDirectory

1 Ответ

2 голосов
/ 05 апреля 2019

Оба подхода кажутся сложными. Если я правильно понимаю, вы хотите построить линейную гистограмму с цветами в зависимости от категории оси X. Как пример:

import matplotlib.pyplot as plt

companies = ["Company A", "Company B", "Company C", "Company D"]
values = [17, 23, 12, 32]

myclient = "Company B"
colors = ["grey" if company is not myclient else "red" for company in companies]

plt.bar(companies, values, color=colors)

plt.show()

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...