Bar chart writing count on the bar

33 views Asked by At

I am trying to write the counts on the bar using bar-plot from matplotlib

import matplotlib.pyplot as plt
data = [
    ["index", "G1", "G2"],
    ["0", 98, 111],
    ["1", 1, 0]
]

# Extract the index and data for plotting
index = [row[0] for row in data[1:]]
G1 = [row[1] for row in data[1:]]
G2 = [row[2] for row in data[1:]]

# Create the bar chart
fig, ax = plt.subplots()
bar_width = 0.35
index = range(len(index))
plt.figure(figsize=(5,5))
plt.bar(index, G1, bar_width, label='G1')
plt.bar([i + bar_width for i in index], G2, bar_width, label='G2')

# Set x-axis labels
plt.xlabel('Test')
plt.xticks([i + bar_width / 2 for i in index], index)

# Add values on top of the bars
for i in range(len(index)):
    plt.text(index[i], G1[i] + 100, str(G1[i]), ha='center')
    plt.text(index[i] + bar_width, G2[i] + 100, str(G2[i]), ha='center')

# Set labels and title
plt.ylabel('Count')
plt.legend()

plt.show()

plt.clf()
plt.cla()
plt.close()

There are two charts generated, one is an empty graph

and, another graph is the actual plot where the text of the bar is goes out of the chart graph

What is the issue, how to solve so that the count of the bar shows on top of the bar instead of printing out of the chart

0

There are 0 answers