简体   繁体   English

相同 x 轴值的不同条形图

[英]Different bar plot for same x-axis value

I'm having a data-frame as follows:我有一个数据框如下:

match_id    team    team_score
  411       RCB       263
 7937       KKR       250
  620       RCB       248
  206       CSK       246
11338       KKR       241
   61       CSK       240
  562       RCB       235

Now, I want to plot a bar plot for all these values as an individual bars, what I'm getting in output is something different:现在,我想为所有这些值绘制一个条形图作为单独的条形,我在输出中得到的是不同的东西:

条形图输出

Is there any way I can make different bars for same x-axis values??有什么办法可以为相同的 x 轴值制作不同的条形?

When 'team' is used as x , all the values for each team are averaged and a small error bar shows a confidence interval.'team'用作x ,每个团队的所有值都是平均的,一个小的误差条显示了置信区间。 To have each entry of the table as a separate bar, the index of the dataframe can be used for x .要将表的每个条目作为单独的条,数据帧的索引可用于x After creating the bars, they can be labeled with the team names.创建条形后,可以用团队名称标记它们。

Optionally, hue='team' colors the bars per team.可选地, hue='team'为每个团队的条形着色。 Then dodge=False is needed to have the bars positioned nicely.然后需要dodge=False才能很好地定位条形。 In that case, Seaborn also creates a legend, which is not so useful, as the same information now also is present as the x-values.在这种情况下,Seaborn 还会创建一个不太有用的图例,因为现在也存在与 x 值相同的信息。 The legend can be suppressed via ax.legend_.remove() .图例可以通过ax.legend_.remove()抑制。

from matplotlib import pyplot as plt
import pandas as pd
from io import StringIO
import seaborn as sns

data_str = StringIO("""match_id    team    team_score
  411       RCB       263
 7937       KKR       250
  620       RCB       248
  206       CSK       246
11338       KKR       241
   61       CSK       240
  562       RCB       235""")
df = pd.read_csv(data_str, delim_whitespace=True)
color_dict = {'RCB': 'dodgerblue', 'KKR': 'darkviolet', 'CSK': 'gold'}
ax = sns.barplot(x=df.index, y='team_score', hue='team', palette=color_dict, dodge=False, data=df)
ax.set_xticklabels(df['team'])
ax.legend_.remove()
plt.tight_layout()
plt.show()

结果图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM