曲线图在x轴中具有不同参数

发布于 2025-02-12 01:23:59 字数 1280 浏览 2 评论 0原文

我有一个类似于下面的数据框。它具有实际和预测的列。我想一对一比较条形图中预测的实际与预测。我具有预测列的置信值,而实际置信度的默认值为1。因此,我想将每一行保持在单条组中,实际和预测的值将为X轴,相应的置信得分为y值。

我无法获得预期的图,因为x轴值在每一行中没有对齐或分组为相同的值。

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

预期的栏图。

任何提示都是可观的。请让我知道是否需要更多详细信息。

到目前为止,我已经尝试过的。

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()

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼眸里的快感 2025-02-19 01:23:59

我发现首先调整数据可以更轻松地获取所需的绘图。我曾经使用过Seaborn,希望还可以。请查看此代码是否适合您。我认为上面提到的df已经可用。我创建了df2,以使其与您在预期数字中显示的内容保持一致。另外,我将索引用作X轴列,以便维护订单...一些调整以确保XTICK名称对齐,传说在您想要的外面。

代码

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

“在此处输入图像说明”

更新 - 对实际和预测的bar

hi @mohammed 分组我认为没有一种方法可以轻松地使用Seaborn来做到这一点。您需要使用matplotlib并调整条位置,XTICK位置等。下面是将执行此操作的代码。您可以将SET1更改为另一个颜色地图以更改颜色。我还添加了一个黑色轮廓,因为相同的彩色条互相融合在一起。此外,我不得不旋转Xlables,因为它们彼此之间。您可以根据自己的要求更改它。希望这对...

vals = df[['Actual','Predicted']].melt(value_name='texts')['texts']
conf = [1]*4 + list(df.Confidence)
ident = ['Actual', 'Predicted']*4
df2 = pd.DataFrame({'Values': vals, 'Confidence':conf, 'Identifier':ident}).reset_index()

uvals, uind = np.unique(df2["Values"], return_inverse=1)
cmap = plt.cm.get_cmap("Set1")

fig, ax=plt.subplots()
l = len(df2)
pos = np.arange(0,l) % (l//2) + (np.arange(0,l)//(l//2)-1)*0.4
ax.bar(pos, df2["Confidence"], width=0.4, align="edge", ec="k",color=cmap(uind)  )  

handles=[plt.Rectangle((0,0),1,1, color=cmap(i), ec="k") for i in range(len(uvals))]
ax.legend(handles=handles, labels=list(uvals), prop ={'size':10}, loc=9, ncol=8) 

pos=pos+0.2
pos.sort()
ax.set_xticks(pos)

ax.set_xticklabels(df2["Identifier"][:l], rotation=45,ha='right', rotation_mode="anchor")
ax.set_ylim(0, 1.2)
plt.show()

输出图

”在此处输入图像说明”

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

Update - grouping Actual and Predicted bars

Hi @Mohammed - As we have already used up hue, I don't think there is a way to do this easily with Seaborn. You would need to use matplotlib and adjust the bar position, xtick positions, etc. Below is the code that will do this. You can change SET1 to another color map to change colors. I have also added a black outline as the same colored bars were blending into one another. Further, I had to rotate the xlables, as they were on top of one another. You can change it as per your requirements. Hope this helps...

vals = df[['Actual','Predicted']].melt(value_name='texts')['texts']
conf = [1]*4 + list(df.Confidence)
ident = ['Actual', 'Predicted']*4
df2 = pd.DataFrame({'Values': vals, 'Confidence':conf, 'Identifier':ident}).reset_index()

uvals, uind = np.unique(df2["Values"], return_inverse=1)
cmap = plt.cm.get_cmap("Set1")

fig, ax=plt.subplots()
l = len(df2)
pos = np.arange(0,l) % (l//2) + (np.arange(0,l)//(l//2)-1)*0.4
ax.bar(pos, df2["Confidence"], width=0.4, align="edge", ec="k",color=cmap(uind)  )  

handles=[plt.Rectangle((0,0),1,1, color=cmap(i), ec="k") for i in range(len(uvals))]
ax.legend(handles=handles, labels=list(uvals), prop ={'size':10}, loc=9, ncol=8) 

pos=pos+0.2
pos.sort()
ax.set_xticks(pos)

ax.set_xticklabels(df2["Identifier"][:l], rotation=45,ha='right', rotation_mode="anchor")
ax.set_ylim(0, 1.2)
plt.show()

Output plot

enter image description here

煮茶煮酒煮时光 2025-02-19 01:23:59

我更新了@Redox的答案以获取确切的输出。

df_ = pd.DataFrame({'Labels': df.reset_index()[['Actual', 'Predicted', 'index']].values.ravel(), 
                   'Confidence': np.array(list(zip(np.repeat(1, len(df)), df['Confidence'].values, np.repeat(0, len(df))))).ravel()})
df_.loc[df_['Labels'].astype(str).str.isdigit(), 'Labels'] = ''

plt.figure(figsize=(15, 6))

ax=sns.barplot(data = df_, x=df_.index, y='Confidence', hue='Labels',dodge=False, ci=None)
ax.set_xticklabels(['Actual', 'Predicted', '']*len(df))
plt.setp(ax.get_xticklabels(), rotation=90)
ax.tick_params(labelsize=14)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

输出:

在此处输入图像描述“

  • 删除循环以提高性能
  • 添加了空白条值以相同的组图表。

I updated @Redox answer to get the exact output.

df_ = pd.DataFrame({'Labels': df.reset_index()[['Actual', 'Predicted', 'index']].values.ravel(), 
                   'Confidence': np.array(list(zip(np.repeat(1, len(df)), df['Confidence'].values, np.repeat(0, len(df))))).ravel()})
df_.loc[df_['Labels'].astype(str).str.isdigit(), 'Labels'] = ''

plt.figure(figsize=(15, 6))

ax=sns.barplot(data = df_, x=df_.index, y='Confidence', hue='Labels',dodge=False, ci=None)
ax.set_xticklabels(['Actual', 'Predicted', '']*len(df))
plt.setp(ax.get_xticklabels(), rotation=90)
ax.tick_params(labelsize=14)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

Output:

enter image description here

  • Removed loop to improve performance
  • Added blank bar values to look alike group chart.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文