用Matplotlib绘制各种图形

一.绘制简单图形

1.折线图

import matplotlib.pyplot as plt
import numpy as np
#单条sin函数
x=np.linspace(0.1, 10, 100)
y=np.sin(x)
plt.plot(x,y, linestyle='-', linewidth=1,label='Sin() by plot()')
plt.legend()
plt.show()
#多条曲线
a=np.random.random((9,3))*2
y1=a[0:,1]
y2=a[0:,2]
x=np.arange(1,10)
ax = plt.subplot(111)#行数,列数,索引值
width=10
hight=3
ax.axes.set_xlim(-0.5,width+0.2)
ax.axes.set_ylim(-0.5,hight+0.2)
plotdict = { 'dx': x, 'dy': y1 }
ax.plot('dx','dy','bD-',data=plotdict)
ax.plot(x,y2,'r^-')
plt.show()

2.柱状图

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
普通柱状图
mpl.rcParams['font.sans-serif']=['SimHei']
x = ['c', 'a', 'd', 'b']
y = [1, 2, 3, 4]
plt.bar(x, y, alpha=0.5, width=0.3, color='yellow', edgecolor='red', label='The First Bar', lw=3)
plt.legend(loc='upper left')
plt.xticks(np.arange(4), ('A','B', 'C', 'D'), rotation=30)
plt.yticks(np.arange(0, 5, 0.4))
plt.ylabel('亏损情况(万元)', fontsize=10)
plt.xlabel('部门', fontsize=10)
plt.title('一季度各部门亏损情况', fontsize=10)
plt.tick_params(axis='both', labelsize=15)
plt.show()

#堆积柱状图
x = [1,3,5]
y = [3,8,9]
y1 = [2,6,3]
plt.bar(x,y,align="center",color="#66c2a5",tick_label=["A","B","C"],label="title_A")
plt.bar(x,y1,align="center",color="#8da0cb",tick_label=["A","B","C"],label="title_B")
plt.legend()
plt.show()

#多数据列柱状图
x = np.arange(3)
y = [2,6,3]
y1 = [6,10,4]
bar_width = 0.4
tick_label = ["A","B","C"]
plt.bar(x,y,align="center",color="c",width=bar_width,label="title_A",alpha=0.5)
plt.bar(x+bar_width,y1,align="center",color="b",width=bar_width,label="title_B",alpha=0.5)
plt.xticks(x+bar_width/2,tick_label)
plt.legend()
plt.show()

#倒影柱状图
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='#9966ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9966', edgecolor='white')
plt.xlim(-.5, n)
plt.ylim(-1.25, 1.25)
for x, y in zip(X, Y1):
    plt.text(x, y + 0.05, '%.2f' % y, ha='center', va='bottom')
for x, y in zip(X, Y2):
    plt.text(x, -y - 0.05, '%.2f' % y, ha='center', va='top')
plt.show()

3.条形图

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(4)
y = [6,10,4,5]
y1 = [2,6,3,8]
bar_width = 0.4
tick_label = ["A","B","C","D"]
plt.barh(x,y,bar_width,align="center",color="c",label="title_A",alpha=1)
plt.barh(x+bar_width,y1,bar_width,align="center",color="b",label="title_B",alpha=1)
plt.yticks(x+bar_width/2,tick_label)
plt.legend()
plt.show()

4.直方图

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
#普通直方图
mu = 100
sigma = 15
x = mu + sigma * np.random.randn(10000)
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='blue', alpha=1)
y = mlab.normpdf(bins, mu, sigma)
plt.show()

#堆积直方图
x1 = np.random.randint(0,100,100)
x2 = np.random.randint(0,100,100)
x = [x1,x2]
colors = ["#fc8d62","#66c2a5"]
labels = ["A","B"]
bins = range(0,101,10)
plt.hist(x,bins=bins,color=colors,histtype="bar",rwidth=10,stacked=True,label=labels,edgecolor = 'k')
plt.show()

5.饼图

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif']=['SimHei']
labels = ["A部门","B部门","C部门","D部门"]
nums = [0.25,0.15,0.36,0.24]
colors = ["#377eb8","#4daf4a","#984ea3","#ff7f00"]
explode = (0.1,0.1,0.1,0.1)
plt.pie(nums,explode=explode,labels=labels,autopct="%3.1f%%",startangle=45,shadow=True,colors=colors)
plt.title("上季度各部门盈利构成")
plt.show()

#嵌套环形图
labels = ["A","B","C","D","E"]
nums1 = [29,19,22,18,12]
nums2 = [22,27,18,11,22]
colors = ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00"]
w1, t1, a1 = plt.pie(nums1,autopct="%3.1f%%",radius=1,pctdistance=0.85,colors=colors,textprops=dict(color="w"),wedgeprops=dict(width=0.3,edgecolor="w"))
w2, t2, a2 = plt.pie(nums2,autopct="%3.1f%%",radius=0.7,pctdistance=0.75,colors=colors,textprops=dict(color="w"),wedgeprops=dict(width=0.3,edgecolor="w"))
plt.setp(a1,size=8,weight="bold")
plt.setp(a2,size=8,weight="bold")
plt.setp(t1,size=8,weight="bold")
plt.show()

6.雷达图

import numpy as np
import matplotlib.pyplot as plt

labels = np.array(['a','b','c','d','e','f'])
dataLenth = 6
data = np.array([2,4,3,6,5,8])
angles = np.linspace(0, 2*np.pi, dataLenth, endpoint=False)
data = np.concatenate((data, [data[0]]))
angles = np.concatenate((angles, [angles[0]]))
plt.polar(angles, data, 'bo-', linewidth=2)
plt.thetagrids(angles * 180/np.pi, labels)
plt.fill(angles, data, facecolor='r', alpha=0.25)
plt.ylim(0,10)
plt.show()

7.散点图

import numpy as np
import matplotlib.pyplot as plt

x1 = np.random.randn(20)
x2 = np.random.randn(20)
plt.figure(1)
#plot画散点图,x取值0,1,2......
plt.plot(x1, 'bo', markersize=20)
plt.plot(x2, 'ro', ms=10,)
plt.show()

8.棉棒图

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 20)
y = np.random.randn(20)
plt.stem(x, y, linefmt='-', markerfmt='o', basefmt='-')
plt.show()

9.箱线图

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

df = pd.DataFrame(np.random.rand(8,5),columns=['A','B','C','D','E'])
df.boxplot()
plt.show()

10.误差棒图

import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import t

X = np.random.randint(5, 15, 15)
n = X.size
X_mean = np.mean(X)
X_std = np.std(X)
X_se = X_std / np.sqrt(n)
dof = n - 1
alpha = 1.0 - 0.95
conf_interval = t.ppf(1-alpha/2., dof) * X_std*np.sqrt(1.+1./n)
fig = plt.gca()
plt.errorbar(1, X_mean, yerr=X_std, fmt='-s')
plt.errorbar(2, X_mean, yerr=X_se, fmt='-s')
plt.errorbar(3, X_mean, yerr=conf_interval, fmt='-s')
plt.xlim([0,4])
plt.ylim(X_mean-conf_interval-2, X_mean+conf_interval+2)
plt.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left="on", right="off", labelleft="on")
plt.show()

#结合条形图
mean_values = [1, 2, 3]
variance = [0.2, 0.4, 0.5]
bar_labels = ['bar 1', 'bar 2', 'bar 3']
fig = plt.gca()
x_pos = list(range(len(bar_labels)))
plt.bar(x_pos, mean_values, yerr=variance, align='center', alpha=0.5)
max_y = max(zip(mean_values, variance))
plt.ylim([0, (max_y[0] + max_y[1]) * 1.1])
plt.xticks(x_pos, bar_labels)
plt.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left="on", right="off", labelleft="on")
plt.show()

11.堆积折线图

import numpy as np
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [1, 3, 4, 2, 7]
y2 = [3, 4, 1, 6, 5]
y3 = [1, 3, 5, 7, 9]
y = np.vstack([y1, y2, y3])
labels = ["Fibonacci ", "Evens", "Odds"]
fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3, labels=labels)
ax.legend(loc='upper left')
plt.show()

12.间断条形图

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors='blue')
ax.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9), facecolors=('red', 'cyan', 'green'))
ax.set_ylim(5, 35)
ax.set_xlim(0, 180)
ax.set_yticks([15, 25])
ax.set_yticklabels(['A', 'B'])
ax.grid(True)
plt.show()

13.阶梯图

import numpy as np
from numpy import ma
import matplotlib.pyplot as plt

x = np.arange(1, 7, 0.4)
y = np.sin(x) + 2.5
plt.step(x, y, label='pre')
y -= 0.5
plt.step(x, y, where='mid', label='mid')
y -= 0.5
plt.step(x, y, where='post', label='post')
plt.legend()
plt.xlim(0, 7)
plt.ylim(0, 4)
plt.show()

二.高级图形

1.对数图

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(1, 10)
y = [10 ** el for el in x]
fig, ax = plt.subplots()
ax.set_yscale('linear')
#对数标度是一条直线
#ax.set_yscale('log')
ax.plot(x, y, color='blue')
ax.grid(True)
plt.show()

2.频谱图

import wave
import matplotlib.pyplot as plt
import numpy as np
import os

f = wave.open('C:\\Users\\Administrator\\.spyder-py3\\V\\test.wav','rb')
params = f.getparams()
nchannels, sampwidth, framerate, nframes = params[:4]
strData = f.readframes(nframes)
waveData = np.fromstring(strData,dtype=np.int16)
waveData = waveData*1.0/(max(abs(waveData)))
waveData = np.reshape(waveData,[nframes,nchannels]).T
f.close()
plt.specgram(waveData[0],Fs = framerate, scale_by_freq = True, sides = 'default')
plt.ylabel('Frequency(Hz)')
plt.xlabel('Time(s)')
plt.show()

3.矢量场流线图

import numpy as np
import matplotlib.pyplot as plt

w = 3
Y, X = np.mgrid[-w:w:100j, -w:w:100j]
U = -1 - X**2 + Y
V = 1 + X - Y**2
speed = np.sqrt(U*U + V*V)
fig, ax = plt.subplots()
ax.streamplot(X, Y, U, V, density=[0.5, 1])
ax.set_title('Varying Density')
plt.show()

4.变量间互相关图

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)
x, y = np.random.randn(2, 100)
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.xcorr(x, y, usevlines=True, maxlags=50, normed=True, lw=2)
ax1.grid(True)
ax1.axhline(0, color='black', lw=2)
ax2 = fig.add_subplot(212, sharex=ax1)
ax2.acorr(x, usevlines=True, normed=True, maxlags=50, lw=2)
ax2.grid(True)
ax2.axhline(0, color='black', lw=2)
plt.show()

三.调整坐标轴和刻度

1.设置坐标轴刻度

from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FormatStrFormatter

ax.set_xlim(0,5)
ax.set_ylim(-1.5,1.5)
ax.xaxis.set_major_locator(MultipleLocator(1))#刻度线每1个单位一个
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(AutoMinorLocator(2))#无数刻度线把有数刻度线之间分割成2段
ax.yaxis.set_minor_locator(AutoMinorLocator(5))

2.设置标签文本

ax.xaxis.set_minor_formatter(FormatStrFormatter('%5.1f'))
ax.yaxis.set_minor_formatter(FormatStrFormatter('%5.1f'))
ax.tick_params(which='minor',length=5,width=1,labelsize=8,labelcolor='r')
ax.tick_params('y',which='major',length=8,width=1,labelsize=10,labelcolor='b')

3.绘制网格线

ax.grid(ls=':',lw=0.8,color='b')

4.移动坐标轴位置

ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

四.添加标题、图例和注释

1.设置标题

plt.title('余弦函数在[-5, 5]的图象', family='kaiti', size=20, color='b', loc='right')

2.设置图例

y1=np.sin(x)
cosine, = ax.plot(x,y,lw=2)
sine, = ax.plot(x,y1,lw=4,ls='--')plt.title('正弦函数和余弦函数在[-5, 5]的图象', family='kaiti', size=20, color='b', loc='left')
plt.legend([sine, cosine], elements, loc='best', prop={'family':'kaiti','size':12})

3.添加注释

ax.annotate('y=sin(x)', xy=(2.5,0.6), xytext=(3.5,0.6), arrowprops=dict(arrowstyle='->', facecolor='black'))
ax.text(-2.1, 0.65, 'y=cos(x)', color='b', bbox=dict(facecolor='black', alpha=0.2))

五.设置线形和文本字体以及颜色

1.设置线形

linestyles=['-','--','-.',':']
linemarkernames=['. 点型',
                'o 圆圈',
                'v 向下的三角形',
                '^ 向上的三角形',
                '< 向左的三角形',
                '> 向右的三角形',
                's 正方形',
                'p 五边形',
                '* 星型',
                '+ +型',
                'x x型',
                '| 竖线',
                '_ 横线']
linemarkerstyles=['.','o','v','^','<','>','s','p','*','+','x','|','_']

2.设置文本和字体属性

families=['arial','tahoma','verdana']
sizes=['xx-small','x-small','small','medium','large','x-large','xx-large']
styles=['normal','italic','oblique']
variants=['normal','small-caps']
weights=['light','normal','medium','roman','semibold','demibold','demi','bold','heavy','extra bold','black']

3.颜色

import scipy.misc
import matplotlib as mpl
import matplotlib.pyplot as plt

#原图
plt.imshow(scipy.misc.ascent())
plt.show()

#white颜色映射
plt.imshow(scipy.misc.ascent(), cmap=mpl.cm.winter)
plt.show()

#RdYlBu颜色映射
plt.imshow(scipy.misc.ascent(), cmap=mpl.cm.RdYlBu)
plt.show()

#Accent颜色映射
plt.imshow(scipy.misc.ascent(), cmap=mpl.cm.Accent)
plt.show()

#灰度映射并添加颜色标尺
plt.imshow(scipy.misc.ascent(), cmap=mpl.cm.gray)
plt.colorbar()
plt.show()

4.划分画布

import scipy.misc
import matplotlib.pyplot as plt

fig, ax=plt.subplots(2,2)
ax[0,0].imshow(scipy.misc.ascent())
ax[0,1].imshow(scipy.misc.ascent(), cmap=mpl.cm.winter)
ax[1,0].imshow(scipy.misc.ascent(), cmap=mpl.cm.RdYlBu)
ax[1,1].imshow(scipy.misc.ascent(), cmap=mpl.cm.Accent)
plt.show()

来源:《python数据分析与可视化》

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值