plt绘制柱状图
先上效果图
数据保存在txt文件中,一列数据。格式如下:
代码如下:
import matplotlib.pyplot as plt
import numpy as np
def show_sub():
all_values = []
x_range = np.arange(-0.05,0.3,0.05)
x_cell = ['~-0.05','-0.05~0','0~0.05','0.05~0.10','0.10~0.15','0.15~0.20','0.20~0.25','0.25~']
y_values = np.zeros(len(x_range))
file = open('sim_sub.txt', 'r')
c = 0
for line in file.readlines():
# if c == 50:
# break
# c += 1
v = line.strip()
all_values.append(v)
file.close()
all_values_arr = np.array(all_values)
all_values_arr = all_values_arr.astype(np.float)
already = 0
for i,x in enumerate(x_range):
idxs = np.where(all_values_arr < x)
y_values[i] = len(idxs[0])-already
if x<=0:
y_values[i] *= -1
already = len(idxs[0])
print(y_values[i])
#all_values = list(all_values_arr)
x_range = list(x_range)
y_values = list(y_values)
x_range.append(0.3)
idxs = np.where(all_values_arr < 1)
rest = len(idxs[0]) - already
y_values.append(rest)
print(x_range)
print(y_values)
x = range(0,len(x_range))
colors = []
for i in y_values:
if i < 0:
colors.append("red")
else:
colors.append("green")
plt.figure(dpi=500)
plt.bar(x=x,tick_label=x_cell, height=y_values, color=colors)
plt.xticks(fontsize=5)
plt.show()
if __name__ == '__main__':
show_sub()