简体   繁体   English

如何在条形图上为每个类别添加观察计数? 使用Matplotlib

[英]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 ) . 我正在使用matplotlib制作一个用于分类变量的图,我需要为每个柱形图( 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 在这里尝试

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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