python中利用matplotlib画图

介绍三种比较简单的方法

  • 基于matplotlib的画图方式
    plt.plot(),常用款
    plt.hist(), 画直方图
    plt.pie(),画饼状图
    plt.figure()
  • 基于pandas的画图
    s.plot() s是pandas的Series对象
    df.plot() df是pandas的DataFrame对象

1.1. plt.plot()#绘制y关于x的变化关系.
x,y是成对出现的。可以省略x,则y是关于y的个数的函数关系。
当y是Series或DataFrame对象对象时,不出现x
[fmt]]可以设置线性,颜色,样式等。

Plot y versus x as lines and/or markers
plot([x], y, [fmt], data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], …, **kwargs)

以一个比较简单的例子入手:

import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

x = np.arange(-10,11)
y = x**2
plt.plot(x,y)

在这里插入图片描述

  • 增加一些功能
    设置标题、坐标轴标签、轴边界、轴刻度、显示中文及正负号
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

x = np.arange(-10,11)
y = x**2
plt.plot(x,y)

#添加标题
plt.title('二次函数')
#设置x,y轴标签
plt.xlabel('x')
plt.ylabel('y')
#设置x,y轴边界
plt.xlim([-12,12])
plt.ylim([-10,110])
#设置x,y轴刻度
plt.xticks([i for i in range(-10,11)])
plt.yticks([i for i in range(-10,101,10)])

plt.rcParams['font.sans-serif']=['SimHei'] #显示中文
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

在这里插入图片描述

  • 增加图例
    配合plot()中的label参数,设置图例。loc设置图例的位置。color设置颜色,linestyle设置颜色,marker设置有值处点的形状。
x = np.arange(-10,11)
y = x**2

plt.plot(x,y,label='y=x^2',color = 'r',linestyle = ':',marker = 'o')
plt.legend(loc = 'upper right')

在这里插入图片描述

  • plt.plot()的参数是Series对象
    在这里插入图片描述
  • plt.plot()的参数是DataFrame对象。DataFrame对象画图时,使用df.plot()更好,图例显示的就是列名。
    在这里插入图片描述
    1.2 plt.hist()画直方图
    1.3. plt.pie()画饼状图
  1. 基于pandas
    2.1 s.plot()
s = pd.Series(np.random.randn(50).cumsum())
s.plot(linestyle = '-.', marker = '_')

在这里插入图片描述
2.2 df.plot()
通过df.plot(kind='line')画图,其中的kind参数可取‘line’,‘bar’,‘kde’(密度图),‘hist’,‘area’(面积图)等。返回对象axes

# 图名,图例,轴标签,轴边界,轴刻度,轴刻度标签等

df = pd.DataFrame(np.random.rand(10,2),columns=['A','B'])
fig = df.plot(figsize=(6,4))
# figsize:创建图表窗口,设置窗口大小
# 创建图表对象,并赋值与fig

plt.title('Interesting Graph - Check it out')  # 图名
plt.xlabel('Plot Number')  # x轴标签
plt.ylabel('Important var') # y轴标签

plt.legend(loc = 'best') 
plt.xlim([0,12])  # x轴边界
plt.ylim([0,1.5])  # y轴边界
plt.xticks(range(11))  # 设置x刻度
plt.yticks([0,0.2,0.4,0.6,0.8,1.0,1.2])  # 设置y刻度
# fig.set_xticklabels("%.1f" %i for i in range(10))  # x轴刻度标签
# 周刻度另命名
fig.set_xticklabels("%c" %i for i in list('abcdegfhij'))  # x轴刻度标签
fig.set_yticklabels("%.2f" %i for i in [0,0.2,0.4,0.6,0.8,1.0,1.2])  # y轴刻度标签

在这里插入图片描述

  • 保存图像plt.savefig('a.png')
  1. 创建子图
    3.1 子图创建1 - 先建立子图然后填充图表
    在子图中添加标题
    ax1.title.set_text('First Plot')
# 子图创建1 - 先建立子图然后填充图表

fig = plt.figure(figsize=(10,6),facecolor = 'gray')

ax1 = fig.add_subplot(2,2,1)  # 第一行的左图
ax1.plot(np.random.rand(50).cumsum(),'r--')
ax1.plot(np.random.randn(50).cumsum(),'b--')
ax1.title.set_text('cumsum -- line')

ax2 = fig.add_subplot(2,2,2)  # 第一行的右图
ax2.hist(np.random.rand(50),alpha=0.5)
ax2.title.set_text('hist')

ax4 = fig.add_subplot(2,2,4)  # 第二行的右图
df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax4.plot(df2,alpha=0.5,linestyle='--',marker='.')
ax2.title.set_text('mess')
plt.show()
# 也可以直接在子图后用图表创建函数直接生成图表

在这里插入图片描述

3.2 创建一个新的figure,并返回一个subplot对象的numpy数组 → plt.subplot

# 子图创建2 - 创建一个新的figure,并返回一个subplot对象的numpy数组 → plt.subplot

fig,axes = plt.subplots(2,3,figsize=(10,4))
ts = pd.Series(np.random.randn(1000).cumsum())
ts2 = pd.Series(np.random.randint(100,size=100))
print(axes, axes.shape, type(axes))
# 生成图表对象的数组

ax1 = axes[0,1]
ax1.plot(ts)
ax2 = axes[0,2]
ax2.plot(ts2)

在这里插入图片描述
参数调整

# plt.subplots,参数调整
fig, axis = plt.subplots(4,4,figsize=(12,10))# 设置子图是4*4,图大小的12*10
fig.suptitle('Histogram')# 添加总标题
# sharex=True,sharey=True。sharex,sharey:是否共享x,y刻度
for i in range(4):
    for j in range(4):
        num = i*4+j+1
        axis[i][j].hist(df_x['f'+str(num)])# 画出f1~f13
        axis[i][j].set_title('f%d' % num)# 设置子图的标题
        if num>=13:
            break
plt.subplots_adjust(wspace=0.3,hspace=0.3)
# wspace,hspace:用于控制宽度和高度的百分比,比如subplot之间的间距

在这里插入图片描述

colorbar配合inshow使用

import numpy as np
from matplotlib import pyplot as plt
m = np.linspace(-100,100,50)
n = np.linspace(-100,100,50)
x,y = np.meshgrid(m,n)
z = x**2 + y**2

plt.imshow(z,cmap='spring')
plt.colorbar(shrink=0.8)# 颜色条占图高的比例
plt.show()

在这里插入图片描述

每行子图数不同

第一行一个子图占据整行。第二行两个子图。
图一是(2,1,1)## 两行一列的子图的第一个

fig = plt.figure(figsize=(10, 10))
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

ax1 = fig.add_subplot(2, 1,1)  # img1
ax2 = fig.add_subplot(2, 2, 3)  # img2
ax5 = fig.add_subplot(2, 2, 4)  # img3

在这里插入图片描述

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值