简体   繁体   中英

How to add a count of observations for each category on a barplot? Using Matplotlib

i'm making a graph using matplotlib for a categorical variable and i need to put the number of observations for each bar ( categorie ) . Can anybody help me? I only find solutions to put manually, but i need to do the same graph for several variables, so i need some code that alredy count the number of observations for each category on a variable. thank u!!

Here is my code:

axis_x =  'Action intended to block/propose policy (block = 1)' 
axis_y = 'Take up'
title = 'neighborhood attract more people'
type = 'bar'
column1 = 'g_scope'
column2 = 'take_up'

database = df
graph_mean_diff_c(column1, column2,  tipo, savename, titulo, eixo_x, eixo_y, database)

Something like this :

在此处输入图片说明

And here the code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import matplotlib.ticker as ticker

N=11
t = np.linspace(0,0.5*np.pi,N)
df = pd.DataFrame({'A':10*np.sin(t),'B':10*np.cos(t)} )

fig = plt.figure(figsize=(15,8))
ax1 = fig.add_subplot(111)

df['A'].plot(kind='barh',width=0.9, color='b', alpha=0.3) 
for y, x in enumerate(df['A']): 
    plt.annotate(str(x)[0:5], xy=(x-0.01, y), va='center',ha='right', color='b', fontweight='bold', fontsize=16)

df['B'].plot(kind='barh',width=0.9, color='r', alpha=0.2) 
for y, x in enumerate(df['B']): 
    plt.annotate(str(x)[0:5], xy=(x-0.01, y), va='center',ha='right', color='r', fontweight='bold', fontsize=16)

x_majorLoc = MultipleLocator(0.5); ax1.xaxis.set_major_locator(x_majorLoc)
#ax.xaxis.set_major_locator(ticker.IndexLocator(base=0.0, offset=0.1))
plt.show()
pic_name='psc_annotaed_bars.png'
fig.savefig(pic_name, transparency=True)

With vertical bars is different. I have tried it here

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM