1. 程式人生 > >python==matplotlib繪圖

python==matplotlib繪圖

1 二維圖形

1.1 線性影象(plot)

import matplotlib.pyplot as plt 
x_data = np.linspace(-1, 1, 10, dtype=np.float32) 
y_data = x_data
plt.plot(x_data, y_data)
plt.xlabel("x_data")
plt.ylabel("y_data")
plt.show()

1.2 散點圖(scatter)

import matplotlib.pyplot as plt 
x_data = np.linspace(-1, 1, 250)
y_data =
x_data plt.scatter(x_data, y_data) plt.show()

1.3 分割槽圖(subplot)

# x, y自給
import matplotlib.pyplot as plt
import numpy as np
a = 0
x_data = np.linspace(-1, 1, 10, dtype=np.float32) 
y_data = x_data
for i in range (4)
	a += 1
	plt.subplot(2,2, a).set_title("Figure {}".format(a))
	plt.plot(x,y)
plt.
show()

1.4 直方圖(histogram)

import numpy as np
import matplotlib.pyplot as plt
def __histogram():
    np.random.seed(19680801)
    mu, sigma = 100, 15
    x = mu + sigma * np.random.randn(10000)
    n, bins, patches = plt.hist(x, 50, normed=1, facecolor='b', alpha=0.75)
    plt.xlabel('Smarts')
    plt.ylabel(
'Probability') plt.title('Histogram of IQ') plt.text(60, .025, r'$\mu=100,\ \sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show() __histogram()

1.5 餅形圖(pie)

  • basic chart
def __pie():
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    sizes = [15, 30, 45, 10]
    explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

    fig1, ax1 = plt.subplots()
    ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=90)
    ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

    plt.show()
__pie()
  • label pie
def __pie():
    fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))

    recipe = ["375 g flour",
              "75 g sugar",
              "250 g butter",
              "300 g berries"]

    data = [float(x.split()[0]) for x in recipe]
    ingredients = [x.split()[-1] for x in recipe]


    def func(pct, allvals):
        absolute = int(pct/100.*np.sum(allvals))
        return "{:.1f}%\n({:d} g)".format(pct, absolute)


    wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
                                      textprops=dict(color="w"))

    ax.legend(wedges, ingredients,
              title="Ingredients",
              loc="center left",
              bbox_to_anchor=(1, 0, 0.5, 1))

    plt.setp(autotexts, size=8, weight="bold")

    ax.set_title("Matplotlib bakery: A pie")

    plt.show()
__pie()

1.6 柱狀圖(bar)

def __bar():
    N = 5
    menMeans = (20, 35, 30, 35, 27)
    womenMeans = (25, 32, 34, 20, 25)
    menStd = (2, 3, 4, 1, 2)
    womenStd = (3, 5, 2, 3, 3)
    ind = np.arange(N)    
    width = 0.35      
	# yerr標準差(圖中黑線)
    p1 = plt.bar(ind, menMeans, width, yerr=menStd)
    # bottom以man為基準
    p2 = plt.bar(ind, womenMeans, width,
                 bottom=menMeans, yerr=womenStd)

    plt.ion()
    plt.ylabel('Scores')
    plt.title('Scores by group and gender')
    plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
    plt.yticks(np.arange(0, 81, 10))
    plt.legend((p1[0], p2[0]), ('Men', 'Women'))
    plt.savefig('images/bar.png', format='png')
    plt.show()
    plt.pause(10)
__bar()

2 三維圖

2.1 曲面(surface)

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def __meshgrid():
    fig = plt.figure()
    ax = Axes3D(fig)
    X = x_data
    Y = y_data
    print(X)
    X,Y = np.meshgrid(X, Y)

    Z = 4- (np.power(X, 2) + np.power(Y, 2))

    # Z = 4 - np.square(x_data, 2) - np.square(y_data, 2)
    # print(Z)
    print("====")
    # print(X)
    print(X.shape)
    print(Z.shape)
    plt.title("Ball")
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.coolwarm)
    ax.set_xlabel('x_data', color='r')
    ax.set_ylabel('y_data', color='r')
    ax.set_zlabel('z_data', color='r')
    plt.show()

__meshgrid()

3 輔助設定

3.1 圖說明設定

plt.title("標題")
plt.xlabel("x軸")
plt.ylabel("y軸")
# 顏色設定
plt.plot(x,y, 'r')
# 點大小設定
plt.scatter(x,y, s=10)
# 分割槽標題
plt.subplot(2,2,2).set_title("標題")
# 圖例+位置
plt.legend(plt.plot(x,y),'圖1', loc='upper right')

3.2 儲存圖片

plt.savefig('path/imageName.png', format='png')

3.3 顯示中文

  • 下載simhei.ttf字型,放至
/home/xdq/.local/lib/python3.6/site-packages/matplotlib/mpl-data/fonts
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']

3.4 調整分割槽圖間距

import matplotlib as plt
plt.subplot(2,2,2)
plt.subplts_adjust(wspace=0.3,hspace=0.5)

更新ing