python==matplotlib绘图

版权声明:转载请注明出处。 https://blog.csdn.net/Xin_101/article/details/84425533

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

猜你喜欢

转载自blog.csdn.net/Xin_101/article/details/84425533