【python】matplotlib(上)

下一篇 【python】matplotlib & seaborn(下)

最近一次修订时间为 2020-10-30



在这里插入图片描述

  • https://matplotlib.org/api/pyplot_api.html (里面有linestyle)(★★★★★)
  • cmap 介绍(★★★★★)


在这里插入图片描述
图片来源:matplotlib 绘图可视化知识点整理


1 Matplotlib 莫烦python

https://morvanzhou.github.io/tutorials/data-manipulation/plt/1-1-why/

1.1 figure

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50) # -1 到 1 50 个点

y1 = 2*x + 1
y2 = x**2

plt.figure()# 下面的都是与 figure 1 相关的
plt.plot(x,y1)

plt.figure(num=3,figsize=(8,5))# 下面的都是 figure 3 的
plt.plot(x,y1,color = "red",linewidth = 10.0,linestyle ="--")
plt.plot(x,y2)

plt.show()

在这里插入图片描述
在这里插入图片描述

1.2 axis

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50) # -1 到 1 50 个点

y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.plot(x,y1,color = "red",linewidth = 1.0,linestyle ="--")
plt.plot(x,y2)

plt.xlim((-1,2))# x轴的范围
plt.ylim((-2,3))# y轴的范围

plt.xlabel("I am x")# x轴的名字
plt.ylabel("I am y")# y轴的名字

new_ticks = np.linspace(-1,2,5) # 新的坐标间距
plt.xticks(new_ticks)# 更换x轴坐标间距

plt.yticks([-2,-1.5,-1,1.22,3],
          ['really bad','bad','normal','good','really good']) #改变y轴的坐标

plt.show()

在这里插入图片描述

可以改变字体,替换一下

plt.yticks([-2,-1.5,-1,1.22,3],
          [r'$really \ bad$',r'$bad \ \alpha$',r'$normal$',r'$good$',r'$really\ good$'])

在这里插入图片描述

改变下坐标轴的位置咯

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50) # -1 到 1 50 个点

y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.plot(x,y1,color = "red",linewidth = 1.0,linestyle ="--")
plt.plot(x,y2)


# gca = get current axis
ax = plt.gca() # x,y

# spines = 上下左右四条黑线
ax.spines['right'].set_color('none') # 让右边的黑线消失
ax.spines['top'].set_color('none')  # 让上边的黑线消失

ax.xaxis.set_ticks_position('bottom') # 把下面的黑线设置为x轴
ax.yaxis.set_ticks_position('left')   #  把左边的黑线设置为y轴

ax.spines['bottom'].set_position(('data',0)) # 移动x轴到指定位置,本例子为0
ax.spines['left'].set_position(('data',0))   # 移动y轴到指定位置,本例子为0


plt.show()

在这里插入图片描述

1.3 legend

在原有的 plt.plot(xxxx) 基础上,加上 label,然后 plt.legend() 就可以实现了

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50) # -1 到 1 50 个点

y1 = 2*x + 1
y2 = x**2

plt.figure()

plt.xlim((-1,2))# x轴的范围
plt.ylim((-2,3))# y轴的范围

plt.xlabel("I am x")# x轴的名字
plt.ylabel("I am y")# y轴的名字

new_ticks = np.linspace(-1,2,5) # 新的坐标间距
plt.xticks(new_ticks)# 更换x轴坐标间距

plt.yticks([-2,-1.5,-1,1.22,3],
          ['really bad','bad','normal','good','really good']) #改变y轴的坐标

plt.plot(x,y2,label = 'up')# 加上 label
plt.plot(x,y1,color = "red",linewidth = 1.0,linestyle ="--",label = 'down')

plt.legend()# 就可以画出 legend了

plt.show()

或者不加 label,用 plt.legend(['up','down']),默认 location 为‘best’,找空位置
在这里插入图片描述

改变标签

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50) # -1 到 1 50 个点

y1 = 2*x + 1
y2 = x**2

plt.figure()

plt.xlim((-1,2))# x轴的范围
plt.ylim((-2,3))# y轴的范围

plt.xlabel("I am x")# x轴的名字
plt.ylabel("I am y")# y轴的名字

new_ticks = np.linspace(-1,2,5) # 新的坐标间距
plt.xticks(new_ticks)# 更换x轴坐标间距

plt.yticks([-2,-1.5,-1,1.22,3],
          ['really bad','bad','normal','good','really good']) #改变y轴的坐标

l1, = plt.plot(x,y2,label = 'up')
l2, = plt.plot(x,y1,color = "red",linewidth = 1.0,linestyle ="--",label = 'down')

plt.legend(handles=[l1,l2,],labels=['square','liner'],loc='best')


plt.show()

l1,l2 的逗号 handles=[l1,l2,]l2 的逗号可以省去

在这里插入图片描述
也可以只显示一个 legend,把 plt.legend(handles=[l1,l2,],labels=['square','liner'],loc='best') 改为
plt.legend(handles=[l1,l2,],labels=['square'],loc='best')
在这里插入图片描述

其中’loc’参数有多种,’best’表示自动分配最佳位置,其余的如下:

 'best' : 0,          
 '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,

loc = '0' 等价于 loc = 'best'

1.4 annotation

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 2*x + 1

# 移动坐标轴到(0,0)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

plt.scatter(x,y) # 画点
plt.show()

plt.scatter(x,y) # 画点

在这里插入图片描述

加 annotation

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 2*x + 1

# 移动坐标轴到(0,0)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

# 定义点
x0 = 1
y0 = 2*x0 + 1
# 画点
plt.scatter(x0,y0,s=50,color='r')
# 画点到x轴的虚线
plt.plot([x0,x0],[0,y0],'k--',lw = 2.5)# x的范围,y的范围,黑色虚线 linewidth

# method1
plt.annotate(r'$2x+1=%s$'% y0, # 表达式
             xy = (x0,y0),#点
             xycoords = 'data',# 这句去掉好像没有影响
             xytext=(+30,-30),#移动表达式
             textcoords = 'offset points',
             fontsize=12,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))#箭头,rad弧度

# method2
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
         fontdict={'size': 12, 'color': 'r'})

plt.plot(x,y)
plt.show()

哈哈,这两个方法参数是真的多
在这里插入图片描述

1.5 tick(能见度)

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 0.1*x

plt.figure()
plt.plot(x,y,linewidth = 10)
plt.ylim(-2,2) 

# 移动坐标轴到(0,0)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

plt.show()

哎呀,难受,图把坐标轴的数字挡了
在这里插入图片描述
比较方便的做法是在 plt.plot(x,y,linewidth = 10) 的时候,加上 zorder,修改如下

plt.plot(x,y,linewidth = 10,zorder = 1)

在这里插入图片描述
还可以在坐标轴上加框框
在上面修改的基础下,添加如下代码

for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_zorder(2)
    # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
    label.set_bbox(dict(facecolor='orange',edgecolor='None', alpha=0.7))

结果如下
在这里插入图片描述

facecolor 是 bbox 的颜色
alpha 是 bbox 的透明度
edgecolor=‘None’ 指的是不要 bbox 的边框,如果删掉的话,效果如下
在这里插入图片描述

1.6 Scatter 画散点图

import matplotlib.pyplot as plt
import numpy as np

n = 1024

X = np.random.normal(0,1,n)# 正态分布
Y = np.random.normal(0,1,n)# 正态分布
C = np.arctan2(Y,X) # for color value

plt.scatter(X,Y,s = 75, c = C,alpha = 0.5)# s = size,c=color

# 设置x轴,y轴的取值范围
plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)

# 去掉x轴,y轴
plt.xticks(())
plt.yticks(())

plt.show()

在这里插入图片描述

1.7 Bar 柱状图

import matplotlib.pyplot as plt
import numpy as np

n = 12 
x = np.arange(n)

# 直线的基础上,加均匀分布的波动
y1 = (1-x/float(n))*np.random.uniform(0.5,1.0,n)
y2 = (1-x/float(n))*np.random.uniform(0.5,1.0,n)

plt.bar(x,+y1,facecolor = '#9999ff',edgecolor = 'orange')
plt.bar(x,-y2,facecolor = '#ff9999',edgecolor = 'orange')

# 给每个条形图加 label,通过 plt.text
for i,j in zip(x,y1):
    # ha: horizontal alignment,va:vertical alignment
    plt.text(i,j+0.1,"%.2f"%j,ha= 'center',va='bottom')
    
for i,j in zip(x,y2):
    # ha: horizontal alignment
    plt.text(i,-j-0.1,"-%.2f"%j,ha= 'center',va='top')

# 设置x,y轴的范围,取消x,y轴的显示
plt.xlim(-.5,n)
plt.xticks(())
plt.ylim(-1.25,1.25)
plt.yticks(())

plt.show()

在这里插入图片描述
感觉不太美

plt.bar(x,+y1,edgecolor = 'white')
plt.bar(x,-y2,edgecolor = 'white')

自然,简单,朴素即是美
在这里插入图片描述

1.8 Contours 等高线图

import matplotlib.pyplot as plt
import numpy as np

def f(x,y):
    # the height function
    return (1-x/2 + x**5 + y**3)*np.exp(-x**2-y**2)

n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)

X,Y = np.meshgrid(x,y)# meshgrid在二维平面中将每一个x和每一个y分别对应起来,编织成栅格:

# use plt.contourf to filling contours
# X,Y and value for (X,Y) point  分成几块图
plt.contourf(X,Y,f(X,Y),9,alpha = 0.75, cmap = plt.cm.hot)
# 也可以写成 cmap = 'hot'

plt.xticks(())
plt.yticks(())
plt.show()

在这里插入图片描述
给等高线描边,添加

# use plt.contour to add contour lines  等高线的黑线
C = plt.contour(X,Y,f(X,Y),9,colors = 'black',linewidths = 1)

在这里插入图片描述

给等高线加 label

# adding label
plt.clabel(C,inline=False,fontsize = 10)

在这里插入图片描述
线把等高线遮住了,不好看,把inline=False 改为 True,或者删掉
在这里插入图片描述

1.9 Image 图片

import matplotlib.pyplot as plt
import numpy as np

# image data
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
              0.365348418405, 0.439599930621, 0.525083754405,
              0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
              
plt.imshow(a,interpolation='nearest',cmap='bone',origin = 'upper')# lower是相反的,interpolation 还有许多其他的方法
plt.colorbar(shrink = 0.9) # colorbar 长度缩减为 90%

plt.xticks(())
plt.yticks(())

plt.show()

在这里插入图片描述
如果是 plt.imshow(a,interpolation='nearest',cmap='bone',origin = 'lower') 的话就反过来了
在这里插入图片描述

interpolation_methods.py,上述例子中我们采用的是 nearest,还有许多其他的插值方式,见 https://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
在这里插入图片描述

plt.imshow(a,interpolation='gaussian',cmap='hot',origin = 'upper') 的效果如下
在这里插入图片描述

1.10 3D 数据

会使用到 np.meshgrid

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)
# X,Y value
X = np.arange(-4,4,0.25)
Y = np.arange(-4,4,0.25)
X,Y = np.meshgrid(X,Y)

R = np.sqrt(X**2 + Y**2)
# height valude
Z = np.sin(R)

# 画 3D 图
ax.plot_surface(X,Y,Z,rstride = 1, cstride = 1, cmap = plt.get_cmap('rainbow'))
# 也可以直接  cmap = 'rainbow'

# 画从Z轴俯视的投影
ax.contourf(X,Y,Z,zdir = 'z',offset = -2, cmap = 'rainbow')
ax.set_zlim(-2,2)

plt.show()

在这里插入图片描述
从 x 方向看过去,投影 ax.contourf(X,Y,Z,zdir = 'x',offset = -4, cmap = 'rainbow')
在这里插入图片描述
如果ax.plot_surface(X,Y,Z,rstride = 5, cstride = 5, cmap = plt.get_cmap('rainbow'))
在这里插入图片描述

1.11 Subplot 多合一显示

import matplotlib.pyplot as plt

plt.figure()
plt.subplot(2,2,1) # 221也行
plt.plot([0,1],[0,1])

plt.subplot(2,2,2)
plt.plot([0,1],[0,2])

plt.subplot(2,2,3)
plt.plot([0,1],[0,3])

plt.subplot(2,2,4)
plt.plot([0,1],[0,4])

plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt

plt.figure()
plt.subplot(2,1,1) # 两行一列第一列占满
plt.plot([0,1],[0,1])

plt.subplot(2,3,4)
plt.plot([0,1],[0,2])

plt.subplot(2,3,5)
plt.plot([0,1],[0,3])

plt.subplot(2,3,6)
plt.plot([0,1],[0,4])

plt.show()

哇,用这种方法就不好画咯,特别要注意数字
在这里插入图片描述

1.11.1 subplot2grid

改进,subplot2grid,这种就灵活很多

import matplotlib.pyplot as plt

# method 1: subplot2grid
plt.figure()
ax1 = plt.subplot2grid((3,3),(0,0),colspan = 3, rowspan = 1) # 三行三列,(0,0)开始,3列,一行
ax1.plot([1,2],[1,2])
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax1.set_title('ax1_title')

ax2 = plt.subplot2grid((3,3),(1,0),colspan = 2, rowspan = 1)
ax3 = plt.subplot2grid((3,3),(1,2),colspan = 1, rowspan = 2)
ax4 = plt.subplot2grid((3,3),(2,0),colspan = 1, rowspan = 1)
ax5 = plt.subplot2grid((3,3),(2,1),colspan = 1, rowspan = 1)

plt.show()

在这里插入图片描述

1.11.2 gridspec

改进,gridspec,根据索引来定位置,五星级推荐这种方法(★★★★★)

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# method 2: gridspec
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:]) # 0行,所有列
ax1 = plt.subplot(gs[1,:2]) 
ax1 = plt.subplot(gs[1:,2]) 
ax1 = plt.subplot(gs[2,0]) 
ax1 = plt.subplot(gs[2,1]) 

plt.show()

在这里插入图片描述
太挤了,没关系,设置一下 figsize plt.figure(figsize=(8,8))
在这里插入图片描述

1.11.3 subplots

import matplotlib.pyplot as plt

# method 3: easy to define structure
f,((ax11,ax12),(ax21,ax22)) = plt.subplots(2,2,sharex = True, sharey = True)
ax11.scatter([1,2],[1,2])

plt.show()

在这里插入图片描述

1.12 图中图

import matplotlib.pyplot as plt

fig = plt.figure()
x = [1,2,3,4,5,6,7]
y = [1,3,4,2,5,8,6]

left,bottom,width,height = 0.1, 0.1, 0.8,0.8 # 起点在左下角
ax1 = fig.add_axes([left,bottom,width,height])
ax1.plot(x,y,'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')

left,bottom,width,height = 0.2, 0.6, 0.25,0.25
ax2 = fig.add_axes([left,bottom,width,height])
ax2.plot(y,x,'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')

# another method, little difference
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1],x,'g') # 倒序 y
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')

plt.show()

在这里插入图片描述

1.13 次坐标轴

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,10,0.1)
y1 = 0.05*x**2
y2 = -1*y1

fig,ax1 = plt.subplots()
ax2 = ax1.twinx() # 镜面反射

ax1.plot(x,y1,'g-')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1',color = 'g')

ax2.plot(x,y2,'b-')
ax2.set_ylabel('Y2',color = 'b')

plt.show()

在这里插入图片描述


下面小节的内容,不属于 莫烦 python 课程内了

1.14 饼图

来自 有趣!如何用Python-matplotlib绘制双层饼图及环形图?

import matplotlib.pyplot as plt

vals = [1, 2, 3, 4]#创建数据系列 
fig, ax = plt.subplots()#创建子图 
labels = 'A', 'B', 'C', 'D' 
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] 
explode = (0, 0.1, 0, 0) # 设置块的间隔
ax.pie(vals, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90,radius=0.9) 
ax.set(aspect="equal", title='Pie plot with `ax.pie`')#设置标题以及图形的对称 

plt.show()

在这里插入图片描述
autopct 是在饼图上显示字的

改进,双饼图

import matplotlib.pyplot as plt

vals1 = [1, 2, 3, 4] 
vals2 = [2, 3, 4, 5] 
fig, ax = plt.subplots() 
labels = 'A', 'B', 'C', 'D' 

ax.pie(vals1, radius=1.2,autopct='%1.1f%%',pctdistance=0.9) # pctdistance(百分比离圆形距离)
ax.pie(vals2, radius=1,autopct='%1.1f%%',pctdistance=0.75) 
ax.pie(vals3, radius=0.6,colors='w') 
ax.set(aspect="equal", title='Pie plot with `ax.pie`') 

#plt.legend() 
plt.legend(labels,bbox_to_anchor=(1, 1), loc='best', borderaxespad=0.) 

plt.show()

在这里插入图片描述

2 How to put the legend outside the map

2.1 加图例

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.5) 
for i in range(1,6):
    y = i/x
    plt.plot(x,y)
plt.legend(["1", "2", "3", "4", "5", "6" ])# 图例
plt.grid()#网格
plt.show()

结果为

2.2 图例放在图像外

图例在图里面,如果曲线特别多的话,图例会挡住部分曲线,效果不好,把图例放在图的外面

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.5) 
for i in range(1,6):
    y = i/x
    plt.plot(x,y)
plt.legend(["1", "2", "3", "4", "5"],loc=2, bbox_to_anchor=(1.0,1.0),borderaxespad = 0.3)
plt.grid()
plt.show()

OK了

2.3 保存图片

however,保存是个问题

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.5) 
for i in range(1,6):
    y = i/x
    plt.plot(x,y)
plt.legend(["1", "2", "3", "4", "5"],loc=2, bbox_to_anchor=(1.0,1.0),borderaxespad = 0.3)
plt.grid()
plt.savefig('1.png')#保存图片
plt.show()

这样保存的结果如下
这里写图片描述

发现图例右半边被切掉了,这样不好
解决办法 plt.subplots_adjust(right=0.8) #将“图”往左边缩放一下,给图例腾出空间

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.5) 
for i in range(1,6):
    y = i/x
    plt.plot(x,y)
plt.legend(["1", "2", "3", "4", "5"],loc=2, bbox_to_anchor=(1.0,1.0),borderaxespad = 0.3)
plt.subplots_adjust(right=0.8) #将“图”往左边缩放一下,给图例腾出空间
plt.grid()
plt.savefig('1.png')
plt.show()

结果为
这里写图片描述

或者 fig.set_size_inches(7, 4)# 设置图片大小

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.5) 
fig,ax = plt.subplots()
for i in range(1,6):
    y = i/x
    plt.plot(x,y)
plt.legend(["1", "2", "3", "4", "5"],loc=2, bbox_to_anchor=(1.0,1.0),borderaxespad = 0.3)
fig.set_size_inches(7, 4)# 设置图片大小
plt.grid()
#plt.subplots_adjust(right=0.8)
plt.savefig('1.png')
plt.show()

结果为
这里写图片描述

当然用截图工具也是可以的,哈哈哈哈哈哈哈

2.4 添加坐标名称和图例名称

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.5) 
fig,ax = plt.subplots()
for i in range(1,6):
    y = i/x
    plt.plot(x,y)
plt.legend(["1", "2", "3", "4", "5"],loc=2, bbox_to_anchor=(1.0,1.0),borderaxespad = 0.3,title = 'coefficient ')
#fig.set_size_inches(7, 4)# 设置图片大小
plt.grid()
plt.subplots_adjust(right=0.8)
plt.xlabel("x")
plt.ylabel("y")
plt.savefig('1.png')
plt.show()

这里写图片描述

2.5 plt.savefig 保存图片时一片空白问题

其实产生这个现象的原因很简单:在 plt.show() 后调用了 plt.savefig() ,在 plt.show() 后实际上已经创建了一个新的空白的图片(坐标轴),这时候你再 plt.savefig() 就会保存这个新生成的空白图片。

错误展示

plt.show()
plt.savefig('test2.jpg')

解决办法
1)在 plt.show() 之前调用 plt.savefig()
2)画图的时候获取当前图像(这一点非常类似于 Matlab 的句柄的概念):

    # gcf: Get Current Figure
    fig = plt.gcf()
    plt.show()
    fig1.savefig('1.png', dpi=100)

3 显示中文

加入如下语句

from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

import numpy as np
import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

font1 = {'size':14} # 设置字体大小

x = np.arange(-10,10,0.1)
y = x**2

plt.grid( linewidth='0.3',linestyle='-')# 格子
plt.xlabel('x 轴',font1)# x轴标签
plt.ylabel('y 轴',font1)# y轴标签
plt.plot(x,y)
plt.show()

在这里插入图片描述

4 图例分列

plt.legend 中的 ncol 属性来控制
for example

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-1,1,0.1)
y0 = x
y1 = x**2
y2 = x**3
y3 = x**4
y4 = 0.5*x
y5 = 0.7*x

plt.grid( linewidth='0.3',linestyle='-')

plt.plot(x,y0)
plt.plot(x,y1)
plt.plot(x,y2)
plt.plot(x,y3)
plt.plot(x,y4)
plt.plot(x,y5)
plt.legend(['1','2','3','4','5','6'],
           loc=2, bbox_to_anchor=(1.0,1.0),borderaxespad = 0.3,ncol=1)# 图例
plt.show()

在这里插入图片描述
ncol=2
在这里插入图片描述
ncol=3
在这里插入图片描述
ncol=6
在这里插入图片描述

5 Cumulative Distribution Function

参考 利用Python的Matplotlib库绘制CDF(累积分布函数)图像

import matplotlib.pyplot as plt
plotDataset = [[],[]]
count = len(sorted_area_list)
for i in range(count):
    plotDataset[0].append(float(sorted_area_list[i]))
    plotDataset[1].append((i+1)/count)

plt.xlabel('XXXXXX')
plt.ylabel('Cumulative Distribution')
#plt.xlim((0,0.3))# x轴的范围
#plt.ylim((0,1))# y轴的范围
plt.plot(plotDataset[0], plotDataset[1], '-', linewidth=2, color=color)
plt.grid(linestyle='--')

plt.savefig('scale_distrubution.png',dpi=300)
plt.show()

哈哈,提高保存分辨率的小trick,plt.savefig中加一句dpi=,参考【python】绘图,控制图的大小和像素

6 Clipping input data to the valid range for imshow with RGB data ([0…1] for floats or [0…255] for integers)

这个报错是在绘制归一化的图片时,没问题,简单的乘以 255 绘制就会报错,这个时候需要把乘 255 后的结果转成无符号的 int8 类型

在这里插入图片描述
来自 stackoverflow上的解答

7 显示自动退出

Python库matplotlib显示图形一定时间后自动关闭

不用 plt.show()

plt.plot(xxx)
#plt.show()
plt.pause(10)  #显示秒数
plt.close()

下一篇 【python】matplotlib & seaborn(下)


参考

【1】python matplotlib如何将图例放在图外
【2】legend 官网
【3】python matplotlib 画图保存图片简单例子
【4】【Python】解决使用 plt.savefig 保存图片时一片空白
【5】matplotlib绘图进阶
【6】Python复杂网络结构可视化——matplotlib+networkx
【7】matplotlib的cmap(★★★)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值