python - 使用 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')
解决方案
正如你在这个例子中看到的,你应该在两个分开的数组中定义X
和Y
,所以你可以这样做:
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()
推荐阅读
- javascript - 删除 Google 表格电子表格中的重复项
- r - dir() 和 list.file() 在 R 中具有非英语名称
- java - 如何检查版本名称字符串(找到)>为Android中的版本名称指定的字符串
- php - 如何获得围绕中心坐标和半径的N个坐标
- php - xdebug.remote_autostart=off 似乎被忽略了
- celery - 如何在气流重启时禁用自动启动所有任务?
- node.js - 无法在猫鼬中聚合查询
- hadoop - Presto 查询无法将数据插入 Hive
- c# - json.deserialize 返回 null + xamarin.forms
- vba - Web crawling Accuweather