首页 > 解决方案 > 使用 Matlplotlib 的条形图

问题描述

我有两个价值观:

test1 = 0.75565

test2 = 0.77615

我正在尝试绘制一个条形图(在 jupyter notebook 中使用 matlplotlib),其中 x 轴作为两个测试值,y 轴作为结果值,但我不断得到一个只有一个大框的疯狂图

这是我尝试过的代码:

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

在此处输入图像描述

标签: pythonpython-3.xmatplotlib

解决方案


正如你在这个例子中看到的,你应该在两个分开的数组中定义XY,所以你可以这样做:

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

最后的情节是这样的: 在此处输入图像描述

更新

如果你想用不同的颜色绘制每个条,你应该多次调用 bar 方法并给它颜色来绘制,尽管它有默认颜色:

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

在此处输入图像描述

或者您可以做得更好并自己选择颜色:

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

在此处输入图像描述


推荐阅读