matplotlib常见图例

1.simple plot

#simple plot
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

#data for plotting
t=np.arange(0.0,2.0,0.01)
s=1+np.sin(2*np.pi*t)

#fig表示整张图纸,ax表示单个子图
fig,ax=plt.subplots()
ax.plot(t,s)

ax.set(xlabel="time(s)",ylabel="voltage(mV)",
       title="simple_plot")

#show the grid
ax.grid()

plt.show()

# =============================================================================
# #data for plotting
# t=np.arange(0.0,2.0,0.01)
# s=1+np.sin(2*np.pi*t)
# plt.figure()
# plt.subplot(111)
# plt.plot(t,s)
# plt.xlabel("time(s)")
# plt.ylabel("voltage(mV)")
# plt.title("simple_plot")
# plt.grid()
# plt.show()
# 
# =============================================================================

2.Multiple subplots(subplot & subplot2grid & gridspec & subplots)

#multiple subplots
import numpy as np
import matplotlib.pyplot as plt
#data
x1=np.linspace(0.0,5.0)
x2=np.linspace(0.0,2.0)

y1=np.cos(2*np.pi*x1)*np.exp(-x1)
y2=np.cos(2*np.pi*x2)

plt.subplot(211)
#o表示点,r表示颜色,--表示虚线
plt.plot(x1,y1,"or--")
plt.title("sample of subplot")
plt.ylabel("Damped oscillation")

plt.subplot(212)
plt.plot(x2,y2, ".g-")
plt.xlabel("time(s)")
plt.ylabel("Undamped")

plt.show()


#subplot2grid
import matplotlib.pyplot as plt
plt.figure()
ax1=plt.subplot2grid((3,3),(0,0),colspan=3)
#使用plt.subplot2grid来创建第1个小图, (3,3)表示将整个图像窗口分成3行3列, 
#(0,0)表示从第0行第0列开始作图,colspan=3表示列的跨度为3, rowspan=1表示行的跨度为1.
#colspan和rowspan缺省, 默认跨度为1.
ax1.plot([1, 2], [1, 2])
ax1.set_title('ax1_title')

#使用plt.subplot2grid来创建第2个小图, (3,3)表示将整个图像窗口分成3行3列, 
#(1,0)表示从第1行第0列开始作图,colspan=2表示列的跨度为2. 同上画出 ax3, 
#(1,2)表示从第1行第2列开始作图,rowspan=2表示行的跨度为2. 再画一个 ax4 和 ax5, 
#使用默认 colspan, rowspan

ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')
ax5 = plt.subplot2grid((3, 3), (2, 1))
plt.show()

#gridspec
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure()
gs = gridspec.GridSpec(3, 3)
#使用gridspec.GridSpec将整个图像窗口分成3行3列. 
#使用plt.subplot来作图, gs[0, :]表示这个图占第0行和所有列,
# gs[1, :2]表示这个图占第1行和第2列前的所有列, 
# gs[1:, 2]表示这个图占第1行后的所有行和第2列, 
# gs[-1, 0]表示这个图占倒数第1行和第0列,
# gs[-1, -2]表示这个图占倒数第1行和倒数第2列.
ax6 = plt.subplot(gs[0, :])
ax6.plot([0,1],[1,2])
ax7 = plt.subplot(gs[1, :2])
ax8 = plt.subplot(gs[1:, 2])
ax8.plot([0,1],[0,6])
ax9 = plt.subplot(gs[-1, 0])
ax9.scatter([0,1],[0,3])
ax10 = plt.subplot(gs[-1, -2])

#subplots
f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])
ax14.plot([3,5],[1,2])
plt.tight_layout()
plt.show()

 

 

 

3.the histogram (hist)

#Demo of the histogram (hist) function with a few features
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
#example data
mu=100#mean od distribution
sigma=15#standard deviation of distribution
x = mu + sigma * np.random.randn(437)
num_bins = 50
fig, ax = plt.subplots()

# the histogram of the data
n, bins, patches = ax.hist(x, num_bins, density=1, facecolor='blue', alpha=0.5)

# add a 'best fit' line
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
     np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
ax.plot(bins, y, '--')
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability density')
ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

4.Three-dimensional plotting

#Three-dimensional plotting
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np


fig = plt.figure()
#gca:Get Current Axes
ax = fig.gca(projection='3d')

# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z,cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

5.Barchart Demo

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from collections import namedtuple


n_groups = 5

means_men = (20, 35, 30, 35, 27)
std_men = (2, 3, 4, 1, 2)

means_women = (25, 32, 34, 20, 25)
std_women = (3, 5, 2, 3, 3)

fig, ax = plt.subplots()

index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.4
error_config = {'ecolor': '0.3'}
rects1 = ax.bar(index, means_men, bar_width,
                alpha=opacity, color='b',
                yerr=std_men, error_kw=error_config,
                label='Men')
rects2 = ax.bar(index + bar_width, means_women, bar_width,
                alpha=opacity, color='r',
                yerr=std_women, error_kw=error_config,
               label='Women')

ax.set_xlabel('Group')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(('A', 'B', 'C', 'D', 'E'))
ax.legend()

fig.tight_layout()
plt.show()

6.Pie charts 

import matplotlib.pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')
#设置explore=explode表示偏移切片,label=label表示显示label,autopct表示饼中数据的显示
#startangle表示开始角度
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

 

7.Log

import numpy as np
import matplotlib.pyplot as plt

# Data for plotting
t = np.arange(0.01, 20.0, 0.01)

# Create figure
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

# log y axis
#semilogy()表示y坐标轴是对数坐标系
ax1.semilogy(t, np.exp(-t / 5.0))
ax1.set(title='semilogy')
ax1.grid()

# log x axis
#semilogx表示x坐标轴为对数坐标系
ax2.semilogx(t, np.sin(2 * np.pi * t))
ax2.set(title='semilogx')
ax2.grid()

# log x and y axis
ax3.loglog(t, 20 * np.exp(-t / 10.0), basex=2)
ax3.set(title='loglog base 2 on x')
ax3.grid()

# With errorbars: clip non-positive values
# Use new data for plotting
x = 10.0**np.linspace(0.0, 2.0, 20)
y = x**2.0

ax4.set_xscale("log", nonposx='clip')
ax4.set_yscale("log", nonposy='clip')
ax4.set(title='Errorbars go negative')
ax4.errorbar(x, y, xerr=0.1 * x, yerr=5.0 + 0.75 * y)
# ylim must be set after errorbar to allow errorbar to autoscale limits
ax4.set_ylim(bottom=0.1)

fig.tight_layout()
plt.show()

8.polar

import numpy as np
import matplotlib.pyplot as plt


r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r

ax = plt.subplot(111, projection='polar')
ax.plot(theta, r)
ax.set_rmax(2)
ax.set_rticks([0.5, 1, 1.5, 2])  # Less radial ticks
ax.set_rlabel_position(-22.5)  # Move radial labels away from plotted line
ax.grid(True)

ax.set_title("A line plot on a polar axis", va='bottom')
plt.show()

参考:https://blog.csdn.net/changzoe/article/details/78845756 

https://matplotlib.org/tutorials/introductory/sample_plots.html#subplot-example

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值