Visualización de datos de Matplotlib desde la entrada hasta el dominio

Reimpreso de: visualización de datos Matplotlib desde la entrada hasta el dominio

Directorio

Prólogo

1. Cómo agregar un título

Segundo, cómo agregar texto-texto

En tercer lugar, cómo agregar anotaciones-anotar

Cuarto, cómo configurar el nombre del eje-xlabel / ylabel

Cinco, cómo agregar una leyenda-leyenda

Seis, cómo ajustar el color.

Siete, cómo cambiar el marcador de estilo de línea

Ocho, cómo mostrar fórmulas matemáticas-texto matemático

Nueve, cómo mostrar la cuadrícula

Diez, cómo ajustar la escala del eje -locator_params

11. Cómo ajustar el eje de coordenadas eje-rango / xlim / ylim

Doce, cómo ajustar la fecha adaptativa -autofmt_xdate

Trece, cómo agregar coordenadas axis-twinx

Catorce, cómo llenar el área -fill / fill_beween

Quince, cómo dibujar una forma llena-matplotlib.patche

16. Cómo cambiar styles-plt.style.use

Más consejos


Prólogo

Matplotlib es una poderosa herramienta de visualización. Es una biblioteca de dibujo de Python. Se puede usar con NumPy y proporciona una alternativa efectiva de código abierto de MatLab.

A continuación se resumen las operaciones y técnicas de uso común para garantizar que el código de cada ejemplo se pueda usar directamente para ejecutar. Para obtener más información, consulte el sitio web oficial.

1. Cómo agregar un título

import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,10)
plt.title('chenqionghe')
plt.plot(x,x*x)
plt.show()

Segundo, cómo agregar texto-texto

Documento oficial
Establecer las coordenadas y el texto

import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-10,11,1)
y=x*x
plt.plot(x,y)
plt.title('chenqionghe')
plt.text(-2.5,30,'function y=x*x')
plt.show()

En tercer lugar, cómo agregar anotaciones-anotar

Documentos oficiales

  • xy: punto de coordenadas para observaciones
  • xytext: las coordenadas del texto de la nota (el valor predeterminado es la posición xy)
  • arrowprops: dibuja una flecha entre xy y xytext
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-10,11,1)
y=x*x
plt.title('chenqionghe')
plt.plot(x,y)
plt.annotate('chenqionghe is  a kind man',xy=(0,1),xytext=(-4,20),arrowprops={'headwidth':10,'facecolor':'r'})
plt.show()

Cuarto, cómo configurar el nombre del eje-xlabel / ylabel

import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,20)
plt.xlabel('chenqionghe')
plt.ylabel('muscle')
plt.plot(x,x*x)
plt.show()

Cinco, cómo agregar una leyenda-leyenda

Documentos oficiales

import numpy as np
import matplotlib.pyplot as plt
plt.plot(x,x)
plt.plot(x,x*2)
plt.plot(x,x*3)
plt.plot(x,x*4)
# 直接传入legend
plt.legend(['chenqionghe','light','weight','baby'])
plt.show()

Seis, cómo ajustar el color.

Pase los parámetros de color, admita los siguientes métodos

import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,5)
#颜色的几种方式
plt.plot(x,color='g')
plt.plot(x+1,color='0.5')
plt.plot(x+2,color='#FF00FF')
plt.plot(x+3,color=(0.1,0.2,0.3))
plt.show()

Siete, cómo cambiar el marcador de estilo de línea

Consulte la documentación oficial para más estilos.

import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,5)
plt.plot(x,marker='o')
plt.plot(x+1,marker='>')
plt.plot(x+2,marker='s')
plt.show()

Ocho, cómo mostrar fórmulas matemáticas-texto matemático

Todos los símbolos de fórmula tienen el
siguiente formato:
como los símbolos de inicio y fin, como los símbolos de inicio y fin, como \ omega $, y los símbolos en la fórmula se resolverán

import numpy as np
import matplotlib.pyplot as plt
plt.title('chenqionghe')
plt.xlim([1,8])
plt.ylim([1,5])
plt.text(2,4,r'$ \alpha \beta \pi \lambda \omega $',size=25)
plt.text(4,4,r'$ \sin(0)=\cos(\frac{\pi}{2}) $',size=25)
plt.text(2,2,r'$ \lim_{x \rightarrow y} \frac{1}{x^3} $',size=25)
plt.text(4,2,r'$ \sqrt[4]{x}=\sqrt{y} $',size=25)
plt.show()

Nueve, cómo mostrar la cuadrícula

import numpy as np
import matplotlib.pyplot as plt
x='chenqionghe','light','weigtht','baby'
y=[15,30,45,10]
plt.grid()
# 也可以设置颜色、线条宽度、线条样式
# plt.grid(color='g',linewidth='1',linestyle='-.')
plt.plot(x,y)
plt.show()

Diez, cómo ajustar la escala del eje -locator_params

Ajuste el eje x y el eje y al mismo tiempo: plt.locator_params (nbins = 20)
solo ajuste el eje x: plt.locator_params ('' x ', nbins = 20)
solo ajuste el eje y: plt.locator_params (' 'y', nbins = 20)

Código de muestra

import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,30,1)
plt.plot(x,x)
# x轴和y轴分别显示20个
plt.locator_params(nbins=20)
plt.show()

11. Cómo ajustar el eje de coordenadas eje-rango / xlim / ylim

  • eje: [0,5,0,10], x de 0 a 5, y de 0 a 10
  • xlim: los parámetros correspondientes son xmin y xmax, que pueden ajustar el máximo y el mínimo respectivamente
  • ylim: igual que el uso de xlim

Código de muestra

import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,30,1)
plt.plot(x,x*x)
#显示坐标轴,plt.axis(),4个数字分别代表x轴和y轴的最小坐标,最大坐标

#调整x为10到25
plt.xlim(xmin=10,xmax=25)
plt.plot(x,x*x)
plt.show()

Doce, cómo ajustar la fecha adaptativa -autofmt_xdate

A veces, la fecha de visualización se superpondrá, lo que es muy hostil. Llame a plt.gcf (). Autofmt_xdate (), el ángulo se ajustará automáticamente

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x=pd.date_range('2020/01/01',periods=30)
y=np.arange(0,30,1)
plt.plot(x,y)
plt.gcf().autofmt_xdate()
plt.show()

Trece, cómo agregar coordenadas axis-twinx

import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,20)
y1=x*x
y2=np.log(x)
plt.plot(x,y1)
# 添加一个坐标轴,默认0到1
plt.twinx()
plt.plot(x,y2,'r')
plt.show()

Catorce, cómo llenar el área -fill / fill_beween

área de función de relleno

import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,5*np.pi,1000)
y1=np.sin(x)
y2=np.sin(2*x)
plt.plot(x,y1)
plt.plot(x,y2)
plt.fill(x,y1,'g')
plt.fill(x,y2,'r')

plt.title('chenqionghe')
plt.show()

llenar_entre el área de intersección de la función de relleno

import numpy as np
import matplotlib.pyplot as plt
plt.title('chenqionghe')
x=np.linspace(0,5*np.pi,1000)
y1=np.sin(x)
y2=np.sin(2*x)
plt.plot(x,y1)
plt.plot(x,y2)
plt.fill_between(x,y1,y2,where=y1>y2,interpolate=True)
plt.show()

Quince, cómo dibujar una forma llena-matplotlib.patche

Consulte los documentos oficiales para varias formas

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mptaches
xy1=np.array([0.2,0.2])
xy2=np.array([0.2,0.8])
xy3=np.array([0.8,0.2])
xy4=np.array([0.8,0.8])

fig,ax=plt.subplots()

#圆形,指定坐标和半径
circle=mptaches.Circle(xy1,0.15)
ax.add_patch(circle)

#长方形
rect=mptaches.Rectangle(xy2,0.2,0.1,color='r')
ax.add_patch(rect)

#多边形
polygon=mptaches.RegularPolygon(xy3,6,0.1,color='g')
ax.add_patch(polygon)

# 椭圆
ellipse=mptaches.Ellipse(xy4,0.4,0.2,color='c')
ax.add_patch(ellipse)

ax.axis('equal')
plt.show()

16. Cómo cambiar styles-plt.style.use

matplotlib admite múltiples estilos, puede cambiar estilos a través de plt.style.use, por ejemplo:

plt.style.use('ggplot')

Ingrese plt.style.availablepara ver todos los estilos

plt.style.available
['seaborn-dark',
 'seaborn-darkgrid',
 'seaborn-ticks',
 'fivethirtyeight',
 'seaborn-whitegrid',
 'classic',
 '_classic_test',
 'fast',
 'seaborn-talk',
 'seaborn-dark-palette',
 'seaborn-bright',
 'seaborn-pastel',
 'grayscale',
 'seaborn-notebook',
 'ggplot',
 'seaborn-colorblind',
 'seaborn-muted',
 'seaborn',
 'Solarize_Light2',
 'seaborn-paper',
 'bmh',
 'tableau-colorblind10',
 'seaborn-white',
 'dark_background',
 'seaborn-poster',
 'seaborn-deep']

Código de muestra

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mptaches

plt.style.use('ggplot')

# 新建4个子图
fig,axes=plt.subplots(2,2)
ax1,ax2,ax3,ax4=axes.ravel()

# 第一个图
x,y=np.random.normal(size=(2,100))
ax1.plot(x,y,'o')

# 第二个图
x=np.arange(0,10)
y=np.arange(0,10)
colors=plt.rcParams['axes.prop_cycle']
length=np.linspace(0,10,len(colors))
for s in length:
    ax2.plot(x,y+s,'-')

# 第三个图
x=np.arange(5)
y1,y2,y3=np.random.randint(1,25,size=(3,5))
width=0.25    

ax3.bar(x,y1,width)
ax3.bar(x+width,y2,width)
ax3.bar(x+2*width,y3,width)

# 第四个图
for i,color in enumerate(colors):
    xy=np.random.normal(size=2)
    ax4.add_patch(plt.Circle(xy,radius=0.3,color=color['color']))
    
ax4.axis('equal')
plt.show()

Estilo predeterminado

Después de cambiar al estilo ggplot

Más consejos

En este punto, las técnicas de uso común son casi las mismas. Se recomienda que lo ejecute usted mismo para profundizar la impresión. Para obtener más técnicas, puede consultar el siguiente artículo

Publicado 314 artículos originales · 22 alabanzas · Más de 20,000 visitas

Supongo que te gusta

Origin blog.csdn.net/qq_39451578/article/details/105403469
Recomendado
Clasificación