2

Each bar has large width

enter image description here

How can I reduce the width of bars, as shown by the drawn red rectangles?

I have the following code in Google Colab.

model_names = ['RFC', 'KNN', 'D-tree',  'SVM RBF']
accuracies = [0.999, 0.970, 0.997, 0.985]

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

ax = sns.barplot(x=model_names, y=accuracies)
plt.xlabel('Model')
plt.ylabel('Accuracy')
plt.title('Model Accuracies Comparison ')

for i, accuracy in enumerate(accuracies):
    ax.annotate('{:.3f}'.format(accuracy), xy=(i, accuracy),      xycoords='data', ha='center', va='bottom', fontsize=10)

plt.show()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
MMH.SE
  • 29
  • 3
  • Hopefully the answer is helpful. Thoroughly answering questions is time-consuming. If your question is **solved**, please _**accept** the solution_. The **✔** is below the **▲/▼** arrow, at the top left of the answer. A new solution can be accepted if a better one shows up. You may also vote on the usefulness of an answer with the **▲/▼** arrow, if you have a 15+ reputation. **Leave a comment if a solution doesn't answer the question.** [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers). – Trenton McKinney Jun 10 '23 at 01:13

1 Answers1

2
  • seaborn v0.12.0 introduced the width parameter to sns.barplot.
    • Google Colab appears to currently be using seaborn 0.12.2 and matplotlib 3.7.1.
    • Also applies to:
      • sns.catplot(data=df, kind='bar', ..., width=0.5)
      • sns.catplot(data=df, kind='count', ..., width=0.5)
      • sns.countplot(data=df, ..., width=0.5)
  • How to add value labels on a bar chart describes using .bar_label.
  • Tested in python 3.11.3, matplotlib 3.7.1, seaborn 0.12.2
import seaborn as sns

# sample dataframe
df = sns.load_dataset('geyser')

# without width
ax = sns.barplot(data=df, x='kind', y='duration', errorbar=None)
ax.set(title='Without width=')
ax.bar_label(ax.containers[0])

# with width
ax = sns.barplot(data=df, x='kind', y='duration', errorbar=None, width=0.5)
ax.set(title='With width=0.5')
ax.bar_label(ax.containers[0])

enter image description here

enter image description here


model_names = ['RFC', 'KNN', 'D-tree',  'SVM RBF']
accuracies = [0.999, 0.970, 0.997, 0.985]

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

# specify width
ax = sns.barplot(x=model_names, y=accuracies, width=0.5)
ax.set(xlabel='Model', ylabel='Accuracy', title='Comparison')

ax.bar_label(ax.containers[0])
ax.margins(y=0.15)

plt.show()

enter image description here

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158