【发布时间】:2017-10-19 06:57:47
【问题描述】:
我的问题与另一个问题有关How to use factorplot to annotate bars with categorical values or to plot 4 variables?
我设法将条形图绘制在一起并放置了第二个轴。但它仅在 Clf 列中有 2 个值时才有效。对于 4 个值,x 轴重复两次。所以不是有 5 组 4 条,而是 10 组 2 条?请查看图片以了解问题。
我认为问题出在这行代码中:
pos = np.arange(0,l) % (l//2) + (np.arange(0,l)//(l//2)-1)*0.4
ax.bar(pos, df["Max_Acc"], width=0.4, align="edge", ec="k", color=colors)
handles=[plt.Rectangle((0,0),1,1, color=palette[i], ec="k") for i in range(len(uelec))]
但我真的不知道如何解决它。
#CODE FOR THE DATAFRAME
raw_data = {'Max_Acc': [90.71, 87.98, 92.62, 78.93, 73.69,
92.62, 94.17, 92.62, 83.81, 79.76,
85.36, 89.23, 88.88, 56.23, 89.54,
36.25, 14.52, 85.45, 75.45, 45.54],
'Stage': ['AWA', 'Rem', 'S1', 'S2', 'SWS',
'AWA', 'Rem', 'S1', 'S2', 'SWS',
'AWA', 'Rem', 'S1', 'S2', 'SWS',
'AWA', 'Rem', 'S1', 'S2', 'SWS'],
'Elec': ['Fp1', 'Fp2', 'C4', 'Cz', 'Pz',
'C4', 'T3', 'Fp1', 'P4', 'Fp2',
'Cz', 'P3', 'P4', 'T4', 'Cp1',
'Cp2', 'T3', 'T4', 'Fp2', 'Fp1'],
'Clf': ['RF', 'RF', 'RF', 'RF', 'RF',
'XG', 'XG', 'XG', 'XG', 'XG',
'SVM','SVM','SVM','SVM','SVM',
'KNN','KNN','KNN','KNN','KNN']}
df=pd.DataFrame(raw_data, columns = ['Max_Acc', 'Stage', 'Elec', 'Clf'])
df
#CODE FOR THE PLOT
#To use seaborn palette
palette = sns.color_palette("Set1", 12)
sns.set(style="white")
uelec, uind = np.unique(df["Elec"], return_inverse=1)
cmap = plt.cm.get_cmap("Set1")
colors= [ palette[i] for i in uind]
fig, ax=plt.subplots(figsize=(15, 5))
l = len(df)
pos = np.arange(0,l) % (l//2) + (np.arange(0,l)//(l//2)-1)*0.4
ax.bar(pos, df["Max_Acc"], width=0.4, align="edge", ec="k", color=colors)
handles=[plt.Rectangle((0,0),1,1, color=palette[i], ec="k") for i in range(len(uelec))]
legend=ax.legend(bbox_to_anchor=(0., 1.15, 1., .102), handles=handles, labels=list(uelec),
prop ={'size':10}, loc=9, ncol=8, title=r'Best algorithm using Max_Acc after undersampling' )
legend.get_frame().set_linewidth(0.0)
plt.setp(legend.get_title(),fontsize='24')
ax.set_xticks(range(l//2))
ax.set_xticklabels(df["Stage"][:l//2])
ax.set_ylim(0, 110)
ax.get_yaxis().set_visible(False)
ax.spines['top'].set_visible(False)
#Double x-axis
ax.set_xticks(pos+0.2, minor=True)
clf=df['Clf'].tolist()
ax.set_xticklabels(clf, minor=True)
plt.setp(ax.get_xticklabels(), rotation=0)
ax.tick_params(axis='x', which='major', pad=25, size=0)
ax=ax
def annotateBars(row, ax=ax):
for p in ax.patches:
ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),
ha='center', va='center', fontsize=11, color='gray', rotation=90, xytext=(0, 20),
textcoords='offset points')
plot = df.apply(annotateBars, ax=ax, axis=1)
图片应该是:
【问题讨论】:
-
您忘记说明绘图是如何从给定的数据帧生成的。
-
如果您在其他(链接)问题中使用代码,我认为问题在于您的
pos数组。把它打印出来,想想它应该是什么......现在它被分成两半,我想这会导致你在这里遇到的问题 -
@ImportanceOfBeingErnest 我已经添加了整个代码。
标签: python pandas matplotlib seaborn