使用Matlplotlib的条形图

2024-09-27 23:17:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个价值观:

test1 = 0.75565

test2 = 0.77615

我试图绘制一个条形图(使用jupyter笔记本中的matlplotlib),其中x轴作为两个测试值,y轴作为结果值,但我一直得到一个只有一个大方框的疯狂图

以下是我尝试过的代码:

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

enter image description here


Tags: 代码绘制bar笔记本jupyterpltwidthlabel
2条回答

绘图显示一个较大值的主要原因是,为列设置的宽度大于已设置的显式x值之间的距离。减小宽度以查看各个列。这样做的唯一好处是,如果出于某种原因需要在条形图上显式设置x值(和y值)。否则,另一个答案就是你需要的“传统条形图”

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

正如您在this example中看到的,您应该在两个分开的数组中定义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()

最终的情节如下: enter image description here

更新

如果要使用不同的颜色绘制每个条形图,应多次调用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()

enter image description here

或者你可以做得更好,自己选择颜色:

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

相关问题 更多 >

    热门问题