tastyminerals
tastyminerals

Reputation: 6548

How to plot a bar plot with matplotlib using two single values?

I am trying to make a bar plot with two values for two classes A and B using matplotlib. My values are a = 43 and b = 21.

I need the plot to look like this:

enter image description here

I have been trying to do it almost an hour using matplotlib examples but eventually gave up. Maybe somebody can help me out?

Upvotes: 3

Views: 5717

Answers (3)

tacaswell
tacaswell

Reputation: 87496

As of mpl 1.5 you can simply do:

import matplotlib.pyplot as plt

fig, ax  = plt.subplots()
ax.bar([1, 2], [43, 21], width=1,
       tick_label=['A', 'B'], align='center')

enter image description here

Upvotes: 3

Hugh Bothwell
Hugh Bothwell

Reputation: 56674

A few variations on fjarri's answer,

  • make it easier to change the number of bars and their values

  • label each bar

like so:

import matplotlib.pyplot as plt
import numpy as np

BAR_WIDTH = 1.     # 0. < BAR_WIDTH <= 1.

def main():
    # the data you want to plot
    categories = ["A", "B"]
    values     = [ 43,  21]
    # x-values for the center of each bar
    xs = np.arange(1, len(categories) + 1)
    # plot each bar centered
    plt.bar(xs - BAR_WIDTH/2, values, width=BAR_WIDTH)
    # add bar labels
    plt.xticks(xs, categories)
    # make sure the chart is centered
    plt.xlim(0, len(categories) + 1)
    # show the results
    plt.show()

main()

which produces

enter image description here

Upvotes: 1

fjarri
fjarri

Reputation: 9726

Use bar():

import matplotlib.pyplot as plt

fig = plt.figure()
s = fig.add_subplot(111)
s.bar([1, 2], [43, 21], width=1)
s.set_xlim(0.5, 3.5)
fig.savefig('t.png')

enter image description here

Edit: following the specs more accurately.

Upvotes: 2

Related Questions