1

I have two values:

test1 = 0.75565

test2 = 0.77615

I am trying to plot a bar chart (using matlplotlib in jupyter notebook) with the x-axis as the the two test values and the y-axis as the resulting values but I keep getting a crazy plot with just one big box

here is the code I've tried:

plt.bar(test1, 1,  width = 2, label = 'test1')
plt.bar(test2, 1,  width = 2, label = 'test2')

enter image description here

2 Answers 2

3

As you can see in this example, you should define X and Y in two separated arrays, so you can do it like this :

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(2)
y = [0.75565,0.77615]

fig, ax = plt.subplots()
plt.bar(x, y)

# set your labels for the x axis here :
plt.xticks(x, ('test1', 'test2'))
plt.show()

the final plot would be like : enter image description here

UPDATE

If you want to draw each bar with a different color, you should call the bar method multiple times and give it colors to draw, although it has default colors :

import matplotlib.pyplot as plt
import numpy as np

number_of_points = 2
x = np.arange(number_of_points)
y = [0.75565,0.77615]

fig, ax = plt.subplots()
for i in range(number_of_points):
    plt.bar(x[i], y[i])

# set your labels for the x axis here :
plt.xticks(x, ('test1', 'test2'))
plt.show()

enter image description here

or you can do it even more better and choose the colors yourself :

import matplotlib.pyplot as plt
import numpy as np

number_of_points = 2
x = np.arange(number_of_points)
y = [0.75565,0.77615]

# choosing the colors and keeping them in a list
colors = ['g','b']

fig, ax = plt.subplots()
for i in range(number_of_points):
    plt.bar(x[i], y[i],color = colors[i])

# set your labels for the x axis here :
plt.xticks(x, ('test1', 'test2'))
plt.show()

enter image description here

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

2 Comments

that worked, thanks! is there any way to change the colors of the two bars?
@JNix Check out the post again
2

The main reason your plot is showing one large value is because you are setting a width for the columns that is greater than the distance between the explicit x values that you have set. Reduce the width to see the individual columns. The only advantage to doing it this way is if you need to set the x values (and y values) explicitly for some reason on a bar chart. Otherwise, the other answer is what you need for a "traditional bar chart".

import matplotlib.pyplot as plt

test1 = 0.75565
test2 = 0.77615

plt.bar(test1, 1,  width = 0.01, label = 'test1')
plt.bar(test2, 1,  width = 0.01, label = 'test2')

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.