Как показать гистограмму в питоне - PullRequest
0 голосов
/ 09 июля 2019

Я пытаюсь создать гистограмму с несколькими барами в Python.Гистограмма должна отображать значения в верхней части каждого бара.У меня есть набор данных, подобный следующему:

Speciality                  Very interested Somewhat_interested Notinterested
Big Data (Spark/Hadoop)         1332           729                      127
Data Analysis / Statistics      1688           444                      60     
Data Journalism                 429            1081                     610

Я пробовал следующий код:

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt

pd_dataframe = pd.read_csv('Test-Barchart.csv')
no_of_xaxis = pd_dataframe.Speciality.nunique()
ind = np.arange(no_of_xaxis)
xcord = pd_dataframe['Speciality'].tolist()

veryinterestedlist = pd_dataframe['Very interested'].tolist()
somewhatlist = pd_dataframe['Somewhat interested'].tolist()
notinterestedlist = pd_dataframe['Not interested'].tolist()

fig=plt.figure()
ax = fig.add_subplot(111)
width=0.8

rects1 = ax.bar(ind, veryinterestedlist, width, color='r')
rects2 = ax.bar(ind, somewhatlist, width, color='g')
rects3 = ax.bar(ind+width*2, notinterestedlist, width, color='b')

ax.legend( (rects1[0], rects2[0], rects3[0]), ('Very Interested', 
 'Somewhat Interested', 'Not Interested') )

def autolabel(rects):
   for rect in rects:
    h = rect.get_height()
    ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
            ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)

ax.set_xticks(ind+width)
ax.set_xticklabels( xcord )
plt.show()

Проблема в том, что plt.show() ничего не показывает!У меня нет ошибок в коде.Не могли бы вы помочь мне решить эту проблему?Также, как я могу изменить цвет бара на шестнадцатеричный код цвета вместо r, g или b?например, # 5bc0de

1 Ответ

0 голосов
/ 09 июля 2019

Небольшие изменения в вашем коде:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

pd_dataframe = pd.read_csv('Test-Barchart.csv')
no_of_xaxis = pd_dataframe.Speciality.nunique()
ind = np.arange(no_of_xaxis)
width = 0.1
xcord = pd_dataframe['Speciality'].tolist()

veryinterestedlist = pd_dataframe['Very interested'].tolist()
somewhatlist = pd_dataframe['Somewhat interested'].tolist()
notinterestedlist = pd_dataframe['Not interested'].tolist()

fig, ax = plt.subplots()

rects1 = ax.bar(ind, veryinterestedlist, width, color='g')
rects2 = ax.bar(ind + width, somewhatlist, width, color='c')
rects3 = ax.bar(ind+2*width, notinterestedlist, width, color='r')

# add some text for labels, title and axes ticks
ax.set_ylabel('y label')
ax.set_title('Title')
ax.set_xticks(ind + width)
ax.set_xticklabels(xcord)

ax.legend( (rects1[0], rects2[0], rects3[0]), ('Very Interested', 
 'Somewhat Interested', 'Not Interested') )

def autolabel(rects):
    """
    Attach a text label above each bar displaying its height
    """
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)

plt.show()

, и вы получите:

enter image description here

Ссылка: Сгруппированная панельдиаграмма с метками

...