天天看点

用matplotlib画双柱形图,并画出横纵轴的箭头

先导入模块

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist  as axisartist
import matplotlib

           

先创建fig对象和其子图ax对象,并使它成为标准的笛卡尔坐标样子

fig=plt.figure()
ax=axisartist.Subplot(fig,111)
fig.add_axes(ax)
ax.axis["left"].set_axisline_style("-|>",size=1.5)
ax.axis["bottom"].set_axisline_style("-|>",size=1.5)
ax.axis["right"].set_visible(False)
ax.axis["top"].set_visible(False)
plt.show()
           

图形如下

用matplotlib画双柱形图,并画出横纵轴的箭头

然后开始画我们的双柱形图:

先把数据写出来

x=np.random.randint(1,50,4)
y=np.random.randint(1,50,4)
z=np.random.randint(1,50,4)
           

现在用bar来画柱形图

width=2.25#设置柱子宽度
a=plt.bar(x,y,width,color="b",label="y")
b=plt.bar(x+width,z,width,color="r",label="z")
           

设置一下柱子上显示数据:

def add_number(rects):
	for i in rects:
		height=i.get_height()
		plt.text(i.get_x()+i.get_width()/2,height,height,ha="center",va="bottom")
add_number(a)
add_number(b)
plt.title("thise a double_bar")
plt.xlabel("x_number")
plt.ylabel("number")
plt.legend(loc="upper right")
plt.show()
           

图形如下

用matplotlib画双柱形图,并画出横纵轴的箭头

因为是随机数,x轴的值靠的太近,跑了好几次有这个结果。

以上。

继续阅读