matplotlib笔记一:基础知识

1、图表的基本元素

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib

# # 图表内基本参数设置
#
# # 图名,图例,轴标签,轴边界,轴刻度,轴刻度标签等
#
# df = pd.DataFrame(np.random.rand(10, 2), columns=['A', 'B'])
# fig = df.plot(figsize=(6, 4))
# # figsize:创建图表窗口,设置窗口大小
# # 创建图表对象,并赋值与fig
#
# plt.title('hello matplotlib')  # 图名
# plt.ylabel('amount')  # y轴标签
# plt.xlabel('dept')  # x轴标签
# plt.ylim([0, 2])  # y轴边界
# plt.xlim([0, 16])  # x轴边界
# plt.legend(loc='upper left')
# # 显示图例,loc表示位置(不是图的位置,而是列名A和B显示的位置)
# # 'best'         : 0, (only implemented for axes legends)(自适应方式)
# # 'upper right'  : 1,
# # 'upper left'   : 2,
# # 'lower left'   : 3,
# # 'lower right'  : 4,
# # 'right'        : 5,
# # 'center left'  : 6,
# # 'center right' : 7,
# # 'lower center' : 8,
# # 'upper center' : 9,
# # 'center'       : 10,
# plt.xticks(range(16))  # 设置x刻度
# plt.yticks(np.arange(0, 2, step=0.2))  # 设置y刻度
# fig.set_xticklabels("%.1f" %i for i in range(16)) # x轴刻度标签
# fig.set_yticklabels("%.1f" %i for i in np.arange(0, 2, step=0.2))  # y轴刻度标签
# # 范围只限定图表的长度,刻度则是决定显示的标尺 → 这里x轴范围是0-12,但刻度只是0-9,刻度标签使得其显示1位小数
# # 轴标签则是显示刻度的标签
# # set_xticklabels和set_yticklabels不能单独使用,必须和xticks、yticks配合使用
# # 否则会报错UserWarning: FixedFormatter should only be used together with FixedLocator

# 其他元素可视性
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, c)
plt.plot(x, s)
# plt.grid(linestyle='--', color='blue', linewidth='2', axis='x')
# 显示网格
# linestyle:线型
# color:颜色
# linewidth:宽度
# axis:x,y,both,显示x/y/两者的格网

# plt.tick_params(bottom='off', top='off', left='off', right='off')
# tick_params参数变了和课程中参数不一样,先搁置

matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'inout'
# 设置刻度的方向,in,out,inout
# 这里需要导入matploltib,而不仅仅导入matplotlib.pyplot

frame = plt.gca()
# plt.axis('off')
# 关闭坐标轴
frame.axes.get_xaxis().set_visible(False)
frame.axes.get_yaxis().set_visible(False)
plt.show()

2、图表的样式参数

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# linestyle、style、color、marker

# linestyle参数

# plt.plot([i**2 for i in range(100)],
#         linestyle = ':')
# '-'       solid line style
# '--'      dashed line style
# '-.'      dash-dot line style
# ':'       dotted line style

# marker参数

# s = pd.Series(np.random.randn(100).cumsum())
# print(s)
# s.plot(linestyle='-', marker='o', color='red')
# '.'       point marker
# ','       pixel marker
# 'o'       circle marker
# 'v'       triangle_down marker
# '^'       triangle_up marker
# '<'       triangle_left marker
# '>'       triangle_right marker
# '1'       tri_down marker
# '2'       tri_up marker
# '3'       tri_left marker
# '4'       tri_right marker
# 's'       square marker
# 'p'       pentagon marker
# '*'       star marker
# 'h'       hexagon1 marker
# 'H'       hexagon2 marker
# '+'       plus marker
# 'x'       x marker
# 'D'       diamond marker
# 'd'       thin_diamond marker
# '|'       vline marker
# '_'       hline marker

# color参数
# plt.hist(np.random.rand(10), color='yellow', alpha=0.4)
# alpha:0-1,透明度
# 常用颜色简写:red-r, green-g, black-k, blue-b, yellow-y

# df = pd.DataFrame(np.random.randn(100, 4),columns=list('ABCD'))
# df = df.cumsum()
# df.plot(style = '--.',alpha = 0.8,colormap = 'GnBu')
# colormap:颜色板,颜色渐变

# 其他参数见“颜色参数.docx”

# style参数,可以包含linestyle,marker,color

# ts = pd.Series(np.random.randn(100).cumsum(), index=pd.date_range('1/1/2000', periods=100))
# ts.plot(style = '--y.',grid = True)
# style → 风格字符串,这里包括了linestyle(-),marker(.),color(g)
# plot()内也有grid参数

# 整体风格样式

import matplotlib.style as psl
print(plt.style.available)
# 查看样式列表
psl.use('ggplot')
ts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000))
ts.plot(style = '--g.',grid = True,figsize=(10,6))
# 一旦选用样式后,所有图表都会有样式,重启后才能关掉

plt.show()

3、刻度、注解、图表输出

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 主刻度、次刻度

# 刻度

from matplotlib.ticker import MultipleLocator, FormatStrFormatter

t = np.arange(0.0, 100.0, 1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)
ax = plt.subplot(111) #注意:一般都在ax中设置,不再plot中设置
plt.plot(t,s,'--*')
plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'both')
# 网格
#plt.legend()  # 图例

xmajorLocator = MultipleLocator(15) # 将x主刻度标签设置为10的倍数
xmajorFormatter = FormatStrFormatter('%.0f') # 设置x轴标签文本的格式
xminorLocator   = MultipleLocator(5) # 将x轴次刻度标签设置为5的倍数
ymajorLocator = MultipleLocator(0.5) # 将y轴主刻度标签设置为0.5的倍数
ymajorFormatter = FormatStrFormatter('%.1f') # 设置y轴标签文本的格式
yminorLocator   = MultipleLocator(0.1) # 将此y轴次刻度标签设置为0.1的倍数

ax.xaxis.set_major_locator(xmajorLocator)  # 设置x轴主刻度
ax.xaxis.set_major_formatter(xmajorFormatter)  # 设置x轴标签文本格式
ax.xaxis.set_minor_locator(xminorLocator)  # 设置x轴次刻度

ax.yaxis.set_major_locator(ymajorLocator)  # 设置y轴主刻度
ax.yaxis.set_major_formatter(ymajorFormatter)  # 设置y轴标签文本格式
ax.yaxis.set_minor_locator(yminorLocator)  # 设置y轴次刻度

ax.xaxis.grid(True, which='both') #x坐标轴的网格使用主刻度
ax.yaxis.grid(True, which='minor') #y坐标轴的网格使用次刻度
# which:格网显示

#删除坐标轴的刻度显示
#ax.yaxis.set_major_locator(plt.NullLocator())
#ax.xaxis.set_major_formatter(plt.NullFormatter())

plt.text(15, 0, 'who am i', fontsize=10)
# df = pd.DataFrame(np.random.randn(10,2))
# df.plot(style = '--o')
# plt.text(5,0.5,'hahaha',fontsize=10)
# 注解 → 横坐标,纵坐标,注解字符串,这里写中文会报错:missing from current font. FigureCanvasAgg.draw(self)

# 图表输出

plt.savefig('C:/lyz/test/pic.png',
            dpi=400,
            bbox_inches = 'tight',
            facecolor = 'g',
            edgecolor = 'b')
# df = pd.DataFrame(np.random.randn(1000, 4), columns=list('ABCD'))
# df = df.cumsum()
# df.plot(style = '--.',alpha = 0.5)
# plt.legend(loc = 'upper left')
# plt.savefig('C:/Users/Hjx/Desktop/pic.png',
#             dpi=400,
#             bbox_inches = 'tight',
#             facecolor = 'g',
#             edgecolor = 'b')
# 可支持png,pdf,svg,ps,eps…等,以后缀名来指定
# dpi是分辨率
# bbox_inches:图表需要保存的部分。如果设置为‘tight’,则尝试剪除图表周围的空白部分。
# facecolor,edgecolor: 图像的背景色,默认为‘w’(白色)

plt.show()

4、子图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 在matplotlib中,整个图像为一个Figure对象
# 在Figure对象中可以包含一个或者多个Axes对象
# 每个Axes(ax)对象都是一个拥有自己坐标系统的绘图区域
#
# plt.figure, plt.subplot

# plt.figure() 绘图对象
# plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None,
# frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, **kwargs)
# fig1 = plt.figure(num=1, figsize=[10,2])
# plt.plot(np.random.rand(50), 'k--')
# fig2 = plt.figure(num=2, figsize=[10,4])
# plt.plot(50 - np.random.rand(50), 'k--')
# num:图表序号,可以试试不写或都为同一个数字的情况,图表如何显示
# figsize:图表大小

# 当我们调用plot时,如果设置plt.figure(),则会自动调用figure()生成一个figure, 严格的讲,是生成subplots(111)

# 子图创建1 - 先建立子图然后填充图表
# fig = plt.figure(figsize=[10,8], facecolor='gray')
# ax1 = fig.add_subplot(2,2,1)
# plt.plot(np.random.randn(50).cumsum(), 'y--')
# plt.plot(np.random.randn(50), 'r--')
# 先创建图表figure,然后生成子图,(2,2,1)代表创建2*2的矩阵表格,然后选择第一个,顺序是从左到右从上到下
# 创建子图后绘制图表,会绘制到最后一个子图

# ax2 = fig.add_subplot(2,2,2)
# plt.hist(np.random.rand(50),alpha=0.5)
#
# ax4 = fig.add_subplot(2,2,4)
# df = pd.DataFrame(np.random.rand(10, 4), columns=list('ABCD'))
# plt.plot(df, alpha=0.8, linestyle='--', marker='.')
# 也可以直接在子图后用图表创建函数直接生成图表

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

fig, axes = plt.subplots(2,3,figsize=[10,4]) # 常用方式
# 生成图表对象的数组
s = pd.Series(np.random.randn(1000).cumsum())
ax1 = axes[0,1]
ax1.plot(s)
axes[0,0].plot(np.random.rand(100))

# plt.subplots,参数调整
# plt.subplots,参数调整

fig,axes = plt.subplots(2,2,sharex=True,sharey=True)
# sharex,sharey:是否共享x,y刻度

for i in range(2):
    for j in range(2):
        axes[i,j].hist(np.random.randn(500),color='k',alpha=0.5)
plt.subplots_adjust(wspace=0,hspace=0)
# wspace,hspace:用于控制宽度和高度的百分比,比如subplot之间的间距

# 子图创建3 - 多系列图,分别绘制

df = pd.DataFrame(np.random.randn(1000, 4), index=s.index, columns=list('ABCD'))
df = df.cumsum()
df.plot(style = '--.',alpha = 0.4,grid = True,figsize = (8,8),
       subplots = True,
       layout = (2,3),
       sharex = False)
plt.subplots_adjust(wspace=0,hspace=0.2)
# plt.plot()基本图表绘制函数 → subplots,是否分别绘制系列(子图)
# layout:绘制子图矩阵,按顺序填充

plt.show()

5、基本图表绘制

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 图表类别:线形图、柱状图、密度图,以横纵坐标两个维度为主
# 同时可延展出多种其他图表样式
#
# plt.plot(kind='line', ax=None, figsize=None, use_index=True, title=None, grid=None, legend=False,
# style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None,
# rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, label=None, secondary_y=False, **kwds)

# Series直接生成图表

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2022', periods=1000))
ts = ts.cumsum()
ts.plot(kind='line', label='x111',style='y--')
# Series.plot():series的index为横坐标,value为纵坐标
# kind → line,bar,barh...(折线图,柱状图,柱状图-横...)
# label → 图例标签,Dataframe格式以列名为label
# style → 风格字符串,这里包括了linestyle(-),marker(.),color(g)
# color → 颜色,有color指定时候,以color颜色为准
# alpha → 透明度,0-1
# use_index → 将索引用为刻度标签,默认为True
# rot → 旋转刻度标签,0-360
# grid → 显示网格,一般直接用plt.grid
# xlim,ylim → x,y轴界限
# xticks,yticks → x,y轴刻度值
# figsize → 图像大小
# title → 图名
# legend → 是否显示图例,一般直接用plt.legend()
# 也可以 → plt.plot()

# Dataframe直接生成图表

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot(kind='line',
       style = '--.',
       alpha = 0.4,
       use_index = True,
       rot = 45,
       grid = True,
       figsize = (8,4),
       title = 'test',
       legend = True,
       subplots = False,
       colormap = 'Greens')
# subplots → 是否将各个列绘制到不同图表,默认False
# 也可以 → plt.plot(df)

plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值