Home > Software engineering >  Plot Bar Graph with different Parametes in X Axis
Plot Bar Graph with different Parametes in X Axis

Time:07-01

I have a DataFrame like below. It has Actual and Predicted columns. I want to compare Actual Vs Predicted in Bar plot in one on one. I have confidence value for Predicted column and default for Actual confidence is 1. So, I want to keep Each row in single bar group Actual and Predicted value will be X axis and corresponding Confidence score as y value.

I am unable to get the expected plot because X axis values are not aligned or grouped to same value in each row.

  Actual Predicted  Confidence
0      A         A        0.90
1      B         C        0.30
2      C         C        0.60
3      D         D        0.75

Expected Bar plot.

enter image description here

Any hint would be appreciable. Please let me know if further details required.

What I have tried so far.

df_actual = pd.DataFrame()
df_actual['Key']= df['Actual'].copy()
df_actual['Confidence'] = 1
df_actual['Identifier'] = 'Actual'

df_predicted=pd.DataFrame()
df_predicted = df[['Predicted', 'Confidence']]
df_predicted = df_predicted.rename(columns={'Predicted': 'Key'})
df_predicted['Identifier'] = 'Predicted'
df_combined = pd.concat([df_actual,df_predicted], ignore_index=True)
df_combined

fig = px.bar(df_combined, x="Key", y="Confidence", color='Identifier',
          barmode='group',  height=400)
fig.show()

enter image description here

CodePudding user response:

I have found that adjusting the data first makes it easier to get the plot I want. I have used Seaborn, hope that is ok. Please see if this code works for you. I have considered that the df mentioned above is already available. I created df2 so that it aligns to what you had shown in the expected figure. Also, I used index as the X-axis column so that the order is maintained... Some adjustments to ensure xtick names align and the legend is outside as you wanted it.

Code

vals= []
conf = []
for x, y, z in zip(df.Actual, df.Predicted, df.Confidence):
    vals  = [x, y]
    conf  = [1, z]
df2 = pd.DataFrame({'Values': vals, 'Confidence':conf}).reset_index()
ax=sns.barplot(data = df2, x='index', y='Confidence', hue='Values',dodge=False)
ax.set_xticklabels(['Actual', 'Predicted']*4)
plt.legend(bbox_to_anchor=(1.0,1))
plt.show()

Plot

enter image description here

  • Related