python matplotlib使用总结

本文详细介绍Matplotlib绘图库的使用方法,包括其强大的绘图能力,如何生成高质量的图形,如折线图、散点图和直方图等。文章深入解析了scatter函数的参数,展示了如何通过代码实现KNN分类器的可视化,以及如何解决中文显示问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、说明

matplotlib是一个python的绘图库,它以各种硬拷贝格式和跨平台的交互式环境出版生成质量级别的图形,它能输出的图形包括折线图,散点图,直方图等,在数据可视化方面,matplotlib拥有数量众多的忠实用户,其强悍的绘图能力能够帮助我们对数据形成非常清晰直观的认知。

matplotlib官网API链接

2、重点函数解释

matplotlib.pyplot.scatter(xys=Nonec=Nonemarker=Nonecmap=Nonenorm=Nonevmin=Nonevmax=Nonealpha=Nonelinewidths=Noneverts=Noneedgecolors=None*data=None**kwargs)[source]

A scatter plot of y vs x with varying marker size and/or color.

Parameters:

x, y : array_like, shape (n, )

The data positions. 一般分别传递数据特性值

s : scalar or array_like, shape (n, ), optional  表示绘制散点的大小

The marker size in points**2. Default is rcParams['lines.markersize'] ** 2.

c : color, sequence, or sequence of color, optional, default: 'b'   一般传递预测目标值y,或者真实目标值_y

The marker color. Possible values:

  • A single color format string.
  • A sequence of color specifications of length n.
  • A sequence of n numbers to be mapped to colors using cmap and norm.
  • A 2-D array in which the rows are RGB or RGBA.

Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2-D array with a single row. Otherwise, value- matching will have precedence in case of a size matching with x and y.

marker : MarkerStyle, optional, default: 'o'  绘制散点的符号

The marker style. marker can be either an instance of the class or the text shorthand for a particular marker. See markers for more information marker styles.

cmap : Colormap, optional, default: None  绘制散点的颜色,传递的是函数,此颜色填充的是散点内部

Colormap instance or registered colormap name. cmap is only used if c is an array of floats. If None, defaults to rc image.cmap.

norm : Normalize, optional, default: None  只有当参数c为浮点数数组时才使用,将数据亮度转化为0-1

Normalize instance is used to scale luminance data to 0, 1. norm is only used if c is an array of floats. If None, use the default colors.Normalize.

vmin, vmax : scalar, optional, default: None

vmin and vmax are used in conjunction with norm to normalize luminance data. If None, the respective min and max of the color array is used. vmin and vmax are ignored if you pass a norm instance.

alpha : scalar, optional, default: None  绘制点的像素百分比,值越大,像素越高,看着点越清晰

The alpha blending value, between 0 (transparent) and 1 (opaque).

linewidths : scalar or array_like, optional, default: None  标记点的长度

The linewidth of the marker edges. Note: The default edgecolors is 'face'. You may want to change this as well. If None, defaults to rcParams lines.linewidth.

edgecolors : color or sequence of color, optional, default: 'face'   传递颜色参数,每次只能传递一种颜色,与cmap功能相似,此颜色绘制的是散点的边界

The edge color of the marker. Possible values:

  • 'face': The edge color will always be the same as the face color.
  • 'none': No patch boundary will be drawn.
  • A matplotib color.

For non-filled markers, the edgecolors kwarg is ignored and forced to 'face' internally.

label:设置每类数据的标签,功能相对于plt.legend()

颜色参数如下b--blue  c--cyan g--green k--black  m--magenta r--red w--white  y--yellow

Returns:

paths : PathCollection

Other Parameters:

**kwargs : Collection properties

from sklearn.datasets import make_blobs
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np

X, y = make_blobs(n_samples=500, centers=5, random_state=8)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y)
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y_train))])

clf = KNeighborsClassifier()
clf.fit(X_train, y_train)

X_min, X_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1

xx, yy = np.meshgrid(np.arange(X_min, X_max, .02), np.arange(y_min, y_max, .02))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.pcolormesh(xx, yy, Z, cmap=plt.cm.spring)

for idx, cl in enumerate(np.unique(y_train)):
    plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cmap, edgecolors='y', marker=markers[idx], alpha=0.8, linewidths=1)

plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("Classifier:KNN")
plt.show()

 


3、code

import matplotlib.pyplot as plt
import matplotlib as mpl

# 解决中文乱码问题
#sans-serif就是无衬线字体,是一种通用字体族。
#常见的无衬线字体有 Trebuchet MS, Tahoma, Verdana, Arial, Helvetica, 中文的幼圆、隶书等等。
mpl.rcParams['font.sans-serif']=['SimHei'] #指定默认字体 SimHei为黑体
mpl.rcParams['axes.unicode_minus']=False #用来正常显示负号


def draw_plt(self):
    """ 绘制路线图,并给路线图中的散点增加标记 """
	colors = ['b', 'g', 'r', 'k', 'm', 'c', 'y']
	labels = ['1', '2', '3', '4', '5', '6']
	for i, routes in enumerate(self.routes):
		color = colors[i]
		xs = []
		ys = []
		for route in routes:
			x, y = self.locations[route - 1][0], self.locations[route - 1][1]
			xs.append(x)
			ys.append(y)
			plt.annotate(route, xy=(x, y), xytext=(x + 0.1, y + 0.1)) # 给点增加标记

		plt.scatter(xs, ys, c=color, s=60, edgecolors=color, marker='o', label=labels[i])
		plt.plot(xs, ys, c=color)

	plt.title('Best total distance is : {:.2f}'.format(self.best_total_distance))
	plt.legend(loc='best')
	plt.xlabel('x')
	plt.ylabel('y')
	plt.savefig("greedy.png")
	plt.show()

4、部分常用函数解释

函数说明
plt.xlim(0,1000)设置x轴的刻度范围为0到1-1000
plt.ylim(0,1000)设置y轴的刻度范围为0到1-1000
plt.scatter(X[:, 0], X[:, 1], s=200, c=y, cmap=plt.cm.spring, edgecolors='k')绘制散点图,s控制绘制点的大小,c为y值,cmap参数是对不同类别的点绘制不同的颜色
plt.title("Classifier:KNN")增加标题
plt.show()显示画图
plt.pcolormesh(xx, yy, Z)将划分开的不同的区域填充不同的颜色,与下面两个函数功能相似
plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)将不同的区域使用颜色填充,使用等高线区分开,xx1和xx2和Z都是等长的数组,cmap为填充颜色函数
plt.contour(xx1, xx2, Z, alpha=0.4, cmap=cmap)使用等高线将不同区域区分开,但是不填充色xx1和xx2和Z都是等长的数组,cmap为填充颜色函数
plt.hlines(y, xmin, xmax, colors='k', linestyles='solid', label='', hold=None, data=None, **kwargs)绘制水平线
plt.legend(loc=(0, 1.05), ncol=2, fontsize=11)显示label name,一般设置参数值loc='best',则显示label到合适的位置
fig1= plt.figure(num="6*2 inches",figsize=(6,2))生成新的图形对象,可以在一个界面同时生成对个图形对象

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值