天天看點

用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軸的值靠的太近,跑了好幾次有這個結果。

以上。

繼續閱讀