在制作图标时需要绘制柱状图,下面对其进行了绘制:主要就是使用matplotlib的
bar
函数。
bar函数官方API为 【matplotlib.pyplot.bar】
下面是从一篇论文中随意截取的一段话,进行后续的绘制图像。
import matplotlib.pyplot as plt
import random
my_list = [random.randint(0, 100) for x in range(12)]
str = "Machine learning models are vulnerable to adversarial examples For the black-box setting"
labels = str.split(" ")
plt.barh(range(len(my_list)), my_list, tick_label=labels)
# plt.ylabel('time(S)') #图像纵坐标的标记
plt.ylabel('time(S)') #图像纵坐标
plt.savefig("./time_bar.jpg") #保存图像
这样绘制出来的图形会发现下面非label全都遮挡了(见下图),所以可以采用将label进行旋转的操作或者将图像的横纵坐标进行变换,达到效果。

label进行旋转后显示:
import matplotlib.pyplot as plt
import random
my_list = [random.randint(0, 100) for x in range(12)]
str = "Machine learning models are vulnerable to adversarial examples For the black-box setting"
labels = str.split(" ")
plt.xticks(rotation=270)
plt.bar(range(len(my_list)), my_list, tick_label=labels)
plt.savefig("./time_bar.jpg") #保存图像
绘制后的图像为:
这里也可以横纵坐标交换,使用
barh
函数即可实现,代码和效果如下:
import matplotlib.pyplot as plt
import random
my_list = [random.randint(0, 100) for x in range(12)]
str = "Machine learning models are vulnerable to adversarial examples For the black-box setting"
labels = str.split(" ")
plt.barh(range(len(my_list)), my_list, tick_label=labels)
# plt.ylabel('time(S)') #图像纵坐标的标记
参考:
【Python——使用matplotlib绘制柱状图】