我有pandas
DataFrame
看起来像这样:
import pandas as pd
temp = pd.DataFrame({'country':['A1','A1','A1','A1','A2','A2','A2','A2'],
'seg': ['S1','S2','S1','S2','S1','S2','S1','S2'],
'agegroup': ['1', '2', '2', '1','1', '2', '2', '1'],
'N' : [21,22,23,24,31,32,33,34]})
我创建了以下图:
sns.factorplot(data=temp, x='seg', y='N', hue='agegroup', row='country', kind='bar',
orient='v', legend=True, aspect=1)
我想做以下事情:
1。将其旋转45度,以使条形水平而不是垂直。我试过这个sns.factorplot(data=temp, x='seg', y='N', hue='agegroup', row='country', kind='bar',
orient='h', legend=True, aspect=1)
但是我收到以下错误TypeError: unsupported operand type(s) for /: 'str' and 'int'
2. 在每个条形图上方放置数字N
。我试着关注this
但我无法使其发挥作用
答案 0 :(得分:1)
您更改了绘图的方向但保留了相同的x,y参数,您需要按如下方式进行交换:
plot = sns.factorplot(data=temp, y='seg', x='N', hue='agegroup', row='country', kind='bar',
orient='h', legend=True, aspect=1)
然后图表将水平渲染。
修改强>
要在条形图上方显示标签,这是我能得到的最接近的标签,希望它可以帮助您:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
temp = pd.DataFrame({'country':['A1','A1','A1','A1','A2','A2','A2','A2'],
'seg': ['S1','S2','S1','S2','S1','S2','S1','S2'],
'agegroup': ['1', '2', '2', '1','1', '2', '2', '1'],
'N' : [21,22,23,24,31,32,33,34]})
plot = sns.factorplot(data=temp, y='seg', x='N', hue='agegroup', row='country', kind='bar',
orient='h', legend=True, aspect=1)
ax = plt.gca()
for p in ax.patches:
ax.text(p.get_width(), p.get_y() + p.get_height()/2., '%d' % int(p.get_width()),
fontsize=12, color='red', ha='right', va='center')