Reputation: 6548
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:
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
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')
Upvotes: 3
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
Upvotes: 1