[英]matplotlib: Setting x tick label on the bar plot to be a range of price
[英]Matplotlib Bar plot only shows the last tick_label
我想用 matplotlib 绘制随机数的条形图。 我单独设置每个tick_label
但只显示最后一个。 哪一个是正确的? 使用tick_label
属性还是使用 plot set_xticks
函数?
import matplotlib.pyplot as plt
import random as r
for i in range(10):
plt.bar(i,i*2, r.randint(1,2) , tick_label=i)
plt.show()
假设您无法提前确定柱的数量(在进入循环之前),您可以循环遍历数字并使用下面的代码即时设置刻度。 如果您有文本标签,则在处理字符串的答案底部还有另一个示例。
import matplotlib.pyplot as plt
import random as r
# initialize labels list
ticklabels = list()
for i in range(10):
# add a bar to the plot
plt.bar(i, r.randint(1, 2))
# append tick to the list & set current axes with
ticklabels.append(i)
plt.xticks(range(len(ticklabels)), labels=ticklabels)
plt.show()
这会产生以下图片
然后,如果你碰巧在循环中也得到了一个字符串标签,你可以将它与plt.xticks
函数的"label"
关键字参数plt.xticks
使用:
import matplotlib.pyplot as plt
import random as r
from string import ascii_uppercase as letters
ticklabels = list()
for i in range(10):
# add a bar to the plot
plt.bar(i, r.randint(1, 2))
# append current tick label
ticklabels.append(letters[r.randint(1, 25)])
# set xaxis ticklabel
plt.xticks(range(len(ticklabels)), labels=ticklabels)
这将产生下面的图片(带有随机标签)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.