mohdsh334
mohdsh334

Reputation: 21

How to show variable names as labels on the x-axis of a histogram?

I have a problem plotting a histogram of the results of my project (3 variables). The results do not appear as desired.

def plot():
    kwargs = dict(alpha=0.9, bins=100)
    plt.hist(Accuracy_of_NB, **kwargs, color='g', label='NB')
    plt.hist(Accuracy_of_SVM, **kwargs, color='b', label='SVM')
    plt.hist(Accuracy_of_MaxEnt, **kwargs, color='r', label='MaxEnt')
    plt.gca().set(title='Show Plotting', xlabel='Accuracy')
    plt.xlim(0,1)
    plt.legend()

the output

I'd like the variable names to appear below the x-axis. On the y axis the values are represented clearly.

Upvotes: 1

Views: 1985

Answers (1)

JohanC
JohanC

Reputation: 80329

As you have only three variables to display, a histogram isn't really adequate. A histogram takes many (hundredths, thousands or more) values, puts them into bins and shows how many values fell into each bin.

A bar plot seems more appropriate. Here is the code for a bar plot with your data. The bars are annotated with their value for better readability. Additional ticks at the y-axis might also be useful.

from matplotlib import pyplot as plt
import matplotlib.ticker as plticker

Accuracy_of_NB = 0.874
Accuracy_of_SVM = 0.871
Accuracy_of_MaxEnt = 0.889

plt.bar(x=['NB', 'SVM', 'MaxEnt'],
        height=[Accuracy_of_NB, Accuracy_of_SVM, Accuracy_of_MaxEnt],
        color=['limegreen', 'dodgerblue', 'crimson'])
ax = plt.gca()
ax.set(title='Comparing accuracies', xlabel='Method', ylabel='Accuracy')
plt.ylim(0, 1)
ax.yaxis.set_major_locator(plticker.MultipleLocator(base=0.1)) # set ticks at the y-axis
ax.yaxis.set_minor_locator(plticker.MultipleLocator(base=0.02)) # set minor ticks at the y-axis

# annotate the bars displaying the value as percentage
for p in ax.patches:
    ax.annotate(f'\n{p.get_height()*100:.1f}%',
      (p.get_x()+p.get_width()/2, p.get_height()), ha='center', va='top', color='white', size=18)
plt.tight_layout()
plt.show()

example bar plot

Upvotes: 1

Related Questions