简体   繁体   中英

Bar Chart using Matlplotlib

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')

在此处输入图片说明

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 : 在此处输入图片说明

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()

在此处输入图片说明

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()

在此处输入图片说明

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')

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM