matplotlib基础学习

从具体的数据图形上手,常见的有饼状图,条形图,以及折线图,散点图,还有如何读取图片文件。以下附上练习代码:

1.饼状图学习案例:

#饼状图学习案例
import matplotlib.pyplot as plt
labels, quants = [], []
file = open('/home/honorwh/Documents/机器学习和数据挖掘/major_country_gdp.csv')
for line in file:
    #print(line)
    info = line.split(',')
    labels.append(info[0])
    quants.append(float(info[1]))
#print(quants, labels)
plt.figure(1, figsize = (6, 6))
colors = ['pink', 'coral', 'yellow', 'orange']
plt.pie(quants, colors = colors, labels = labels, autopct = '%1.1f%%', pctdistance = 0.8, shadow = True)
plt.title('Top 10 GDP Countries', bbox = {'facecolor': '0.8', 'pad': 5})
plt.show()

2.条形图学习案例:

#条形图学习案例
import matplotlib.pyplot as plt
import numpy as np
labels, quants = [], []
file = open('/home/honorwh/Documents/机器学习和数据挖掘/major_country_gdp.csv')
for line in file:
    info = line.split(',')
    labels.append(info[0])
    quants.append(float(info[1]))

width = 0.4
ind = np.linspace(0.5, 9.5, 10)
fig = plt.figure(1, figsize = (12, 6))
ax = fig.add_subplot(111)
ax.bar(ind - width // 2, quants, width, color = 'coral')
ax.set_xticks(ind)
ax.set_xticklabels(labels)
ax.set_xlabel('Country')
ax.set_ylabel('GDP (Billion US dollar)')
ax.set_title('Top 10 GDP Countries', bbox = {'facecolor': '0.8', 'pad': 5})
plt.show()

3.函数式绘图:

#函数式绘图
import matplotlib.pyplot as plt
plt.plot([0, 1], [0, 1])
plt.title("a strait line")
plt.xlabel("x value")
plt.ylabel("y value")
plt.savefig("demo.jpg")

4.折线图,散点图等的数据绘图程序及读取图片:

#数据绘图程序
import matplotlib.pyplot as plt
#1D Data

x = [1, 2, 3, 4, 5]
y = [2.3, 3.4, 1.2, 6.6, 7.0]
plt.figure(figsize = (12, 6))
#折线图
plt.subplot(231)
plt.plot(x, y)
plt.title("plot")

#散点图
plt.subplot(232)
plt.scatter(x, y)
plt.title("scatter")

#饼状图
plt.subplot(233)
plt.pie(y)
plt.title("pie")

#条形图
plt.subplot(234)
plt.bar(x, y)
plt.title("bar")

#2D Data
import numpy as np
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = Y ** 2 + X ** 2

plt.subplot(235)
plt.contour(X, Y, Z)
plt.colorbar()
plt.title("contour")

#read image
import matplotlib.image as mpimg
img = mpimg.imread("/home/honorwh/ml.jpg")

plt.subplot(236)
plt.imshow(img)
plt.title("imshow")

plt.savefig("matplot_sample.jpg")

最后一张是我随机选取读取一张壁纸,这个过程是在Ipython运行的,包括截取图片。这次先对matplotlib有了一定的上手操作经验,对这几种常见的图形绘制逐步熟悉,之后会通过更多的案例来上手,也算是对可视化的学习迈出第一步。

猜你喜欢

转载自blog.csdn.net/honorwh/article/details/89702861