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

2024-06-16 13:02:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用matplotlib为一个分类变量绘制一个图,我需要为每个条(categorie)输入观察值的数量。有人能帮我吗?我只找到手动放置的解决方案,但我需要为几个变量绘制相同的图形,因此我需要一些代码,以便计算变量上每个类别的观察值数量。谢谢你

这是我的密码:

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)

Tags: 图形数量matplotlib绘制分类手动解决方案block
1条回答
网友
1楼 · 发布于 2024-06-16 13:02:15

像这样:

enter image description here

代码如下:

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)

与竖条不同。我试过了 here

enter image description here

相关问题 更多 >