0

I am trying to add data labels to a horizontal bar chart. The data looks something like this,

Category = ['Communication',
 'Entertainment',
 'Family Support',
 'Food',
 'Healthcare',
 'House Rent',
 'Lending',
 'Transportation']

Cost = [-3100, -1299, -15000, -9127, -5000, -12000, -1000, -2100]

plt.barh(df['Category'], df['Cost'])

The chart without data labels

I want data labels at the end of each bar in the image above. Please help!

Salahuddin
  • 37
  • 1
  • 11
  • Maybe you find [this](https://stackoverflow.com/questions/28931224/adding-value-labels-on-a-matplotlib-bar-chart) useful. – Mohammad Khoshbin Dec 12 '21 at 17:42
  • Does this answer your question? [Adding value labels on a matplotlib bar chart](https://stackoverflow.com/questions/28931224/adding-value-labels-on-a-matplotlib-bar-chart) – Mohammad Khoshbin Dec 12 '21 at 17:42

1 Answers1

1

Adding xlabel and ylabel should solve,

plt.xlabel("Cost")
plt.ylabel("Category")

You might also want to create the dataframe:

import pandas as pd
df = {}
df["Category"] = Category
df["Cost"] = Cost
df = pd.DataFrame.from_dict(df)

For adding the data value of each of the bar you can modify your code as follows:

# First make a subplot, so that axes is available containing the function bar_label.
fig, ax = plt.subplots()
g=ax.barh(df['Category'], df['Cost'])
ax.set_xlabel("Cost")
ax.set_ylabel("Category")
ax.bar_label(g, label_type="center") # This provides the labelling, this only available at higher version. You can do pip install -U matplotlib
plt.show()

Reference:

  1. Axis Label
  2. matplotlib 3.4.2 and above has this

Output:
Output

coldy
  • 2,115
  • 2
  • 17
  • 28
  • Hello! Thank you for your response. However, I am looking to add data labels to the bars and not x and y labels. – Salahuddin Dec 12 '21 at 17:48
  • 1
    Hello, I have updated the answer, as you can see data values within each bar now. There are more operations to them such as padding which you can refer from the original documentation. – coldy Dec 12 '21 at 18:07