3

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?

0

3 Answers 3

3

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

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

2 Comments

out of interest, which part is new in 1.5? tick_label?
Yes, added link to whats new page to answer.
2

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.

4 Comments

Minor detail, but I believe OP needs width=1.0:)
Yes, I guess. I didn't like how it looked, but for the sake of accuracy I'll fix it.
Compromise with color='w',edgecolor='k',lw=5?:)
And xkcd style too, probably. Left as an exercise for OP :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.