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!

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hello! Thank you for your response. However, I am looking to add data labels to the bars and not x and y labels.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.