Панды, как отображать процент вместе с гистограммой - PullRequest
1 голос
/ 04 ноября 2019

Я уже строю гистограмму для данных ниже

                Total Monthly Actual Hours  Total Monthly Work Hours
Activity Month
Apr-19          35381.25                    42592
May-19          31722.50                    44528
Jun-19          27708.50                    38720
Jul-19          34283.50                    44528
Aug-19          21359.90                    42592

.

Мой код до сих пор

display(dfWorkActual)

dfWorkActual.plot(kind='bar')
plt.ylabel('Work Hours')
plt.xlabel('Month')
plt.title("Total Monthly Work Hours & Total Actual Work Hours vs Month")

Chart

А теперь я хотел бы добавить процент от общего фактического часа от общего месячного часа.

Например:

enter image description hereenter image description here enter image description here

Пожалуйста, сообщите

Ответы [ 2 ]

1 голос
/ 04 ноября 2019

Для аннотирования гистограммы вы можете обратиться к примеру из документации по matplotlib здесь.

https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py

fig = plt.figure(figsize=(15,10))
ax = plt.gca()
width = 0.35
rects1 = ax.bar(df.index-width/2, df.A, width)
rects2 = ax.bar(df.index+width/2, df.B, width)
for r1, r2 in zip(rects1, rects2):
    h1 = r1.get_height()
    h2 = r2.get_height()
    percent = int(h1 * 100 / h2)
    ax.annotate('{}%'.format(percent),
                    xy=(r1.get_x() + r1.get_width() / 2, h1),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')
    ax.annotate('100%',
                    xy=(r2.get_x() + r2.get_width() / 2, h2),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

plt.show()

enter image description here

и

fig = plt.figure(figsize=(15,10))
ax = plt.gca()
width = 0.35
rects1 = ax.bar(df.index, df.A, width)
rects2 = ax.bar(df.index, df.B, width, bottom=df.A)
for r1, r2 in zip(rects1, rects2):
    h1 = r1.get_height()
    h2 = r2.get_height()
    percent = int(h1 * 100 / h2)
    ax.annotate('{}%'.format(percent),
                    xy=(r1.get_x() + r1.get_width() / 2, h1/2),
                    xytext=(0, 0),
                    textcoords="offset points",
                    ha='center', va='bottom')
    ax.annotate('100%',
                    xy=(r2.get_x() + r2.get_width() / 2, h1+h2/2),
                    xytext=(0, 0), 
                    textcoords="offset points",
                    ha='center', va='bottom')

plt.show()

enter image description here

1 голос
/ 04 ноября 2019

Что вы можете сделать, это аннотировать некоторый текст на графике таким образом

for x,y,tex in zip(x_axis, abs_value, perc_value):
        t = ax.text(x, 
                    y, 
                    f"{tex:.2f} %", 
                    horizontalalignment='center',
                    verticalalignment='center',
                    size = 11.5, 
                    bbox = dict(boxstyle="round", 
                                fc="w", 
                                ec='#414141', 
                                linewidth=1.4))

, где x_axis - это список с точкой, в которой лежат столбцы. abs_value - это список с высотой столбцов, а perc_value - это список с процентами. Я поместил некоторые другие элементы в текст, например, bbox создаст округлую белую коробку с процентом внутри. Поиграйте с параметрами, чтобы получить лучшее для вашей цели. Как видите, я размещаю текст f"{tex:.2f} %" по координатам (x, y). Надеюсь, это поможет.

...