python使用matplotlib绘图

想在论文中使用python画图,之前就在知乎上看到有大神讲解用python中的matplotlib工具进行画图,并且说这个工具十分强大,今天我就打算学习学习,也算是入门,就参考了几个人的博客,找到了一些常用的图形的画法,把他们都画了出来,代码也附在这里,也方便以后使用的时候查看。越学习这个工具越觉着这个工具十分强大,在文末也放上了画廊的地址,可以在那里看到许多高大上的绘图,然而他们实现的代码都很简单,最令人惊奇的是,python居然还可以实现类似于手写稿的效果。

折线图

plot 方法的关键字参数 color(或c) 用来设置线的颜色。可取值为:

颜色名称或简写

  • b: blue
  • g: green
  • r: red
  • c: cyan
  • m: magenta
  • y: yellow
  • k: black
  • w: white
    #rrggbb
    (r, g, b) 或 (r, g, b, a),其中 r g b a 取均为[0, 1]之间
    [0, 1]之间的浮点数的字符串形式,表示灰度值。0表示黑色,1表示白色

样式

plot 方法的关键字参数 linestyle(或ls) 用来设置线的样式。可取值为:

‘-‘, ‘solid’
‘–’, ‘dashed’
‘-.’, ‘dashdot’
‘:’, ‘dotted’
‘’, ‘ ‘, ‘None’

legend 方法可接受一个 loc 关键字参数来设定图例的位置,可取值为数字或字符串:

  • ‘best’
  • ‘upper right’
  • ‘upper left’
  • ‘lower left’
  • ‘lower right’
  • ‘right’
  • ‘center left’
  • ‘center right’
  • ‘lower center’
  • ‘upper center’
  • ‘center’

marker

以下关键字参数可以用来设置marker的样式:

marker
markeredgecolor 或 mec
markeredgewidth 或 mew
markerfacecolor 或 mfc
markerfacecoloralt 或 mfcalt
markersize 或 ms
其中 marker 可取值为:

‘.’: 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’: thindiamond marker
‘|’: vline marker
‘: hline marker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#coding:utf-8
# http://syaning.com/2017/02/06/matplotlib-line
# 折线图

import numpy as np
import matplotlib.pyplot as plt

#plt.rcParams['font.sans-serif']=['simhei'] #用来正常显示中文标签
#plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
#有中文出现的情况,需要u'内容'

#X轴的文字
plt.xlabel("X轴")

#Y轴的文字
plt.ylabel("Y轴")

#图表的标题
plt.title("图表标题")

x = np.linspace(0, 2 * np.pi, 10)
y1 = [0.5,0.8,1,3,3,4.5,5,6,1,2]
y2 = [0.3,0.4,2,5,3,4.5,4,5,4,2]

plt.plot(x, y1, marker='o', mec='r', mfc='w', label='y1图例')
plt.plot(x, y2, marker='*', ms=10, label='y2图例')

plt.legend()
plt.show()

png

并列柱状图

plt.bar函数签名为:

1
bar(left, height, width=0.8, bottom=None, **kwargs)

事实上,left,height,width,bottom这四个参数确定了柱体的位置和大小。默认情况下,left为柱体的居中位置(可以通过align参数来改变left值的含义),即:

1
2
(left - width / 2, bottom)为左下角位置
(left + width / 2, bottom + height)为右上角位置

hatch 关键字可用来设置填充样式,可取值为: / , \ , | , - , + , x , o , O , . , * 。例如:

1
2
3
4
5
6
import matplotlib.pyplot as plt

data = [5, 20, 15, 25, 10]

plt.bar(range(len(data)), data, ec='k', lw=1, hatch='o')
plt.show()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import numpy as np
import matplotlib.pyplot as plt

size = 5
x = np.arange(size)
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)

total_width, n = 0.8, 3
width = total_width / n
x = x - (total_width - width) / 2

plt.bar(x, a, width=width, label='a')
plt.bar(x + width, b, width=width, label='b')
plt.bar(x + 2 * width, c, width=width, label='c')
plt.legend()
plt.show()

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import numpy as np
from matplotlib import pyplot as plt
plt.figure(figsize=(9,6))
n = 8
X = np.arange(n)+1
#X是1,2,3,4,5,6,7,8,柱的个数
# numpy.random.uniform(low=0.0, high=1.0, size=None), normal
#uniform均匀分布的随机数,normal是正态分布的随机数,0.5-1均匀分布的数,一共有n个
Y1 = np.random.uniform(0.5,1.0,n)
Y2 = np.random.uniform(0.5,1.0,n)
plt.bar(X,Y1,width = 0.35,facecolor = 'lightskyblue',edgecolor = 'white')
#width:柱的宽度
plt.bar(X+0.35,Y2,width = 0.35,facecolor = 'yellowgreen',edgecolor = 'white')
#水平柱状图plt.barh,属性中宽度width变成了高度height
#打两组数据时用+
#facecolor柱状图里填充的颜色
#edgecolor是边框的颜色
#想把一组数据打到下边,在数据前使用负号
#plt.bar(X, -Y2, width=width, facecolor='#ff9999', edgecolor='white')
#给图加text
for x,y in zip(X,Y1):
plt.text(x+0.3, y+0.05, '%.2f' % y, ha='center', va= 'bottom')

for x,y in zip(X,Y2):
plt.text(x+0.6, y+0.05, '%.2f' % y, ha='center', va= 'bottom')
plt.ylim(0,+1.25)
plt.show()

png

散点图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import numpy as np
from matplotlib import pyplot as plt

plt.figure(figsize=(9,6))
n=1000
#rand 均匀分布和 randn高斯分布
x=np.random.randn(1,n)
y=np.random.randn(1,n)
T=np.arctan2(x,y)
plt.scatter(x,y,c=T,s=25,alpha=0.4,marker='o')
#T:散点的颜色
#s:散点的大小
#alpha:是透明程度
plt.show()

png

饼状图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# -*- coding: utf-8 -*-  
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

def draw_pie(labels,quants):
# make a square figure
plt.figure(1, figsize=(6,6))
# For China, make the piece explode a bit
expl = [0,0.1,0,0,0,0,0,0,0,0] #第二块即China离开圆心0.1
# Colors used. Recycle if not enough.
colors = ["blue","red","coral","green","yellow","orange"] #设置颜色(循环显示)
# Pie Plot
# autopct: format of "percent" string;百分数格式
plt.pie(quants, explode=expl, colors=colors, labels=labels, autopct='%1.1f%%',pctdistance=0.8, shadow=True)
plt.title('Top 10 GDP Countries', bbox={'facecolor':'0.8', 'pad':5})
plt.show()

# quants: GDP

# labels: country name

labels = ['USA', 'China', 'India', 'Japan', 'Germany', 'Russia', 'Brazil', 'UK', 'France', 'Italy']
quants = [15094025.0, 11299967.0, 4457784.0, 4440376.0, 3099080.0, 2383402.0, 2293954.0, 2260803.0, 2217900.0, 1846950.0]
draw_pie(labels,quants)

png

折线图进阶

参考网址:http://blog.csdn.net/u011497262/article/details/52325705

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8,5), dpi=80)
ax = plt.subplot(111)
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))

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")


plt.xlim(X.min()*1.1, X.max()*1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

plt.ylim(C.min()*1.1,C.max()*1.1)
plt.yticks([-1, +1],
[r'$-1$', r'$+1$'])

plt.legend(loc='upper left', frameon=False)

t = 2*np.pi/3
plt.plot([t,t],[0,np.cos(t)],
color ='blue', linewidth=1.5, linestyle="--")
plt.scatter([t,],[np.cos(t),], 50, color ='blue')
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

plt.plot([t,t],[0,np.sin(t)],
color ='red', linewidth=1.5, linestyle="--")
plt.scatter([t,],[np.sin(t),], 50, color ='red')
plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65 ))

# plt.savefig("../figures/exercice_10.png",dpi=72)
plt.show()

png

好玩的绘图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import numpy as np
import matplotlib.pyplot as plt

eqs = []
eqs.append((r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$"))
eqs.append((r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$"))
eqs.append((r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$"))
eqs.append((r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$"))
eqs.append((r"$F_G = G\frac{m_1m_2}{r^2}$"))


plt.axes([0.025,0.025,0.95,0.95])

for i in range(24):
index = np.random.randint(0,len(eqs))
eq = eqs[index]
size = np.random.uniform(12,32)
x,y = np.random.uniform(0,1,2)
alpha = np.random.uniform(0.25,.75)
plt.text(x, y, eq, ha='center', va='center', color="#11557c", alpha=alpha,
transform=plt.gca().transAxes, fontsize=size, clip_on=True)

plt.xticks([]), plt.yticks([])
# savefig('../figures/text_ex.png',dpi=48)
plt.show()

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import mlab

np.random.seed(0)

mu = 200
sigma = 25
n_bins = 50
x = np.random.normal(mu, sigma, size=100)

fig, ax = plt.subplots(figsize=(8, 4))

# plot the cumulative histogram
n, bins, patches = ax.hist(x, n_bins, normed=1, histtype='step',
cumulative=True, label='Empirical')

# Add a line showing the expected distribution.
y = mlab.normpdf(bins, mu, sigma).cumsum()
y /= y[-1]

ax.plot(bins, y, 'k--', linewidth=1.5, label='Theoretical')

# Overlay a reversed cumulative histogram.
ax.hist(x, bins=bins, normed=1, histtype='step', cumulative=-1,
label='Reversed emp.')

# tidy up the figure
ax.grid(True)
ax.legend(loc='right')
ax.set_title('Cumulative step histograms')
ax.set_xlabel('Annual rainfall (mm)')
ax.set_ylabel('Likelihood of occurrence')

plt.show()

png

参考网址

Matplotlib 画廊 简直太有用了!!里面各种高大上的绘图,如果有需要的话可以打开看看,找到好看的就点击图片就会跳转到他的代码,复制下来,看懂了就可以画出自己的图了!!强烈推荐。

本文作者:Qiu Qingyu
版权声明:本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0 CN许可协议。转载请注明出处!
本文永久链接:http://qiuqingyu.cn/2017/05/16/python使用matplotlib绘图/