简体   繁体   中英

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??

When 'team' is used as x , all the values for each team are averaged and a small error bar shows a confidence interval. To have each entry of the table as a separate bar, the index of the dataframe can be used for x . After creating the bars, they can be labeled with the team names.

Optionally, hue='team' colors the bars per team. Then dodge=False is needed to have the bars positioned nicely. 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. The legend can be suppressed via 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()

结果图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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