python数据分析之(6)简单绘图matplotlib.pyplot

本文介绍了Matplotlib的基本用法,包括使用plot()函数绘制不同类型的线条、调整线条属性、创建多图像布局及添加文本说明等内容。

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

matplotlib.pyplot是一些命令行风格函数的集合,使matplotlib以类似于MATLAB的方式工作。每个pyplot函数对一幅图片(figure)做一些改动:比如创建新图片,在图片创建一个新的作图区域(plotting area),在一个作图区域内画直线,给图添加标签(label)等。matplotlib.pyplot是有状态的,亦即它会保存当前图片和作图区域的状态,新的作图函数会作用在当前图片的状态基础之上。

(1)使用plot()函数画图
plot()为画线函数,下面的小例子给ploy()一个列表数据[1,2,3,4],matplotlib假设它是y轴的数值序列,然后会自动产生x轴的值,因为python是从0作为起始的,所以这里x轴的序列对应为[0,1,2,3]。

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('numbers')  #给y轴加注释
plt.show()


plot()还可以接受x,y成对的参数,还有一个可选的参数是表示线的标记和颜色,plot函数默认画线是蓝色实线,即字符串'b-',你可以选择自己喜欢的标记和颜色。

import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,8,27,64], 'ro')
plt.axis([0, 6, 0, 80])
plt.show()

axis()函数给出了形如[xmin,xmax,ymin,ymax]的列表,指定了坐标轴的范围。给出一个numpy数组(arrays),给出不同的线。

import numpy as np
import matplotlib.pyplot as plt
f= np.arange(0, 5, 0.1)
# red dashes, blue squares and green triangles
plt.plot(f, f, 'r--', f, f**2, 'bs', f, f**3, 'g^')
plt.show()
(2)线的属性
可以用不同方式对线的属性进行设置:
用参数的关键字:plt.plot(x, y, linewidth=2.0)通过这种方式修改线宽;

使用Line2D实例的set方法:
plot函数返回一个线的列表,比如line1,line2 = plot(x1,y1,x2,y2)。由于我们只有一条直线,对于长度为1的列表(list),我们可以用逗号,来得到列表第一个元素

使用pyplot的setp()命令
还可以用setp()命令来进行设置,该命令可以对一个列表或者单个对象进行设置,并且提供了matlab式的使用方法

(3)多个图像
pyplot和MATLAB一样,都有当前图像和当前坐标的概念,所有命令都是对当前的坐标进行设置。

import numpy as np
import matplotlib.pyplot as plt
def f(t):
	return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
subplot()命令会指定一个坐标系,默认是subplot(111),111参数分别说明行的数目numrows,列的数目numcols,第几个图像fignum(fignum的范围从1到numrows*numcols)。
subplot(211)指定显示两行,每行一图,接下来为第一幅图像。


(4)为图像做文本说明
text()命令可以用于在任意位置添加文本,而xlabel(),ylabel(),title()用来在指定位置添加文本。所有的text()命令返回一个matplotlib.text.Text实例,也可以通过关键字或者setp()函数对文本的属性进行设置。

import numpy as np
import pylab as pl

data = np.random.normal(0,2,100)
# make a histogram of the data array
pl.hist(data)
 
# make plot labels
pl.xlabel('distribute')
pl.ylabel('Probability')
pl.title('Histogram')
pl.text(0, 40, r'$\mu=0,\ \sigma=2$')
pl.axis([-10, 10, 0, 50])
#pl.grid(True)
pl.show()

matplotlib从1.1.0版本以后就开始支持绘制动画,网取的示例:

import numpy as np 
from matplotlib import pyplot as plt 
from matplotlib import animation 
# First set up the figure, the axis, and the plot element we want to animate 
fig = plt.figure() 
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) 
line, = ax.plot([], [], lw=2) 
# initialization function: plot the background of each frame 
def init(): 
  line.set_data([], []) 
  return line, 
# animation function. This is called sequentially 
# note: i is framenumber 
def animate(i): 
  x = np.linspace(0, 2, 1000) 
  y = np.sin(2 * np.pi * (x - 0.01 * i)) 
  line.set_data(x, y) 
  return line, 
# call the animator. blit=True means only re-draw the parts that have changed. 
anim = animation.FuncAnimation(fig, animate, init_func=init, 
                frames=200, interval=20, blit=True) 
#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264']) 
plt.show() 


关于导出GIF动态图,参见:http://www.hankcs.com/ml/using-matplotlib-and-imagemagick-to-realize-the-algorithm-visualization-and-gif-export.html,

还没试过。

参考:

http://www.cnblogs.com/wei-li/archive/2012/05/23/2506940.html

http://www.tuicool.com/articles/7zYNZfI

http://www.cnblogs.com/kemaswill/archive/2012/12/07/2807963.html

### Python 数据分析可视化 `matplotlib.pyplot` 使用教程 #### 导入库并准备数据 为了使用 `matplotlib.pyplot` 进行数据分析和可视化,首先需要导入必要的库。这里展示如何创建简单的折线图。 ```python import matplotlib.pyplot as plt data = [1, 2, 3, 4, 5, 4, 2, 4, 6, 7] plt.plot(data) # 调用 plot 方法绘制折线图[^1] plt.xlabel('X轴标签') # 添加 X 轴标签 plt.ylabel('Y轴标签') # 添加 Y 轴标签 plt.title('简单折线图示例') # 设置图表标题 plt.show() # 显示图像窗口 ``` 这段代码展示了基本的数据可视化流程:先定义要可视化的数据集;接着调用相应的方法来设置坐标轴名称、图表标题等属性;最后通过 `show()` 函数显示所生成的图形界面。 #### 绘制多种类型的图表 除了基础的折线图外,还可以利用该库轻松制作更多种类的统计图表,比如柱状图、饼图以及箱型图等。 对于想要在同一张图片里呈现多个不同系列的情况,可以传递二维数组给绘图函数作为输入参数: ```python import numpy as np x_values = np.random.rand(10) y_values_1 = x_values * 2 + 1 y_values_2 = -x_values ** 2 + 3 fig, ax = plt.subplots() ax.scatter(x_values, y_values_1, c='blue', label="Line 1") # 散点图 ax.plot(x_values, y_values_2, 'r-', lw=2, label="Curve 2") # 折线图 ax.legend(loc='best') plt.grid(True) plt.show() ``` 上述例子中不仅包含了散点图与折线图的同时展现方式,还加入了网格线辅助阅读,并且设置了图例帮助区分不同的线条或标记样式[^2]。 当涉及到更复杂的统计数据表示形式时,如箱型图,则可以通过调整特定选项来自定义外观效果: ```python np.random.seed(19680801) all_data = [np.random.normal(0, std, size=100) for std in range(1, 4)] labels = ['A', 'B', 'C'] colors = ['#D4EFDF', '#EDEDED', '#FAD7A0'] box_properties = dict(linewidth=2, color='black') flierprops = dict(marker='o', markerfacecolor='#e7298a', markersize=8, linestyle='none') medianprops = {'linestyle': '-', 'linewidth': 2, 'color': 'firebrick'} meanpointprops = {'marker':'D', 'markeredgecolor':'green', 'markerfacecolor':'forestgreen'} bplot = plt.boxplot(all_data, labels=labels, patch_artist=True, boxprops=dict(facecolor="#ccffcc"), flierprops=flierprops, medianprops=medianprops, meanprops=meanpointprops, showcaps=False, showmeans=True) for patch, color in zip(bplot['boxes'], colors): patch.set_facecolor(color) plt.xticks(rotation=45) plt.tight_layout() plt.show() ``` 此部分代码片段说明了怎样配置箱型图的各项特性,包括但不限于背景填充色(`patch_artist`)、异常值符号风格(`flierprops`)、平均数指示器形状(`meanprops`)等等[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值