python 画图

python画图代码集合

2017-08-13  本文已影响0人  与尔岩说

matplotlib介绍

基本图形展现

使用plot函数,首先收藏链接:http://matplotlib.org/contents.html

%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,3,2,4],[1,3,2,7],'ro')
plt.ylabel('some numbers')
plt.axis([0, 6, 0, 20])
plt.show()

上面例子里的plot里的list规定了x和y,如果缺省一个则将视为y值,后面的‘ro’表示红色的圈圈,可以做修改;
axis()命令给定了坐标范围,格式是[xmin, xmax, ymin, ymax];
实际上,matplotlib不仅可以用于画向量,还可以用于画多维数据数组。

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

格式设置

线形设置

有很多线的性质可供你设置:线宽,虚线格式,反锯齿补偿,等。进一步深入了解参数可以参见matplotlib.lines.Line2D

·我们可以通过'linewidth'来设置线宽,通过设定set_antialiased来确定是否消除锯齿

line = plt.plot([1,2,3,4], [1,4,9,16], '-', linewidth=2.0)
line.set_antialiased(False) # 关闭反锯齿

面我们都只画了一条线。这里,我们采用lines = plot(x1,y1,x2,y2)来画两条线。可以使用setp()命令,可以像MATLAB一样设置几条线的性质。 setp可以使用python 关键词,也可用MATLAB格式的字符串。(plt.setp(lines))

lines = plt.plot([1,2,3,4], [1,4,9,16], [1,2,3,4], [16,5,6,2])
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

我们在作图中经常用到的性质都在以下列表中给出了:
线型包括

线型  描述
'-' 实线
'--'    虚线
'-.'    点划线
':' 点
'None', '', 不画

线标记包括

标记  描述
'o' 圆圈
'D' 钻石
'h' 六边形1
'H' 六边形2
'x' X
'', 'None'  不画
'8' 八边形
'p' 五角星
',' 像素点
'+' 加号
'.' 点
's' 正方形
'*' 星型
'd' 窄钻石
'v' 下三角
'<' 左三角
'>' 右三角
'^' 上三角

颜色 所有的颜色设置可以通过命令matplotlib.pyplot.colors()来查询

标记  颜色
'b' 蓝色
'g' 绿色
'r' 红色
'c' 蓝绿色
'm' 品红
'y' 黄色
'k' 黑色
'w' 白色

如果上面的颜色还是不够用,可以采用RGB3元组来定义,范围是0~1
比如:color = (0.3, 0.3, 0.4)
color可以被用在一系列和函数中,这里我们再title中改变color

修改坐标范围

默认情况下,坐标轴的最小值和最大值与输入数据的最小、最大值一致。也就是说,默认情况下整个图形都能显示在所画图片上,我们可以通过xlim(xmin, xmax)和ylim(ymin, ymax)来调整x,y坐标范围,见下:

xlim(-2.5, 2.5)
#设置y轴范围
ylim(-1, 1)
plt.plot(x, y1)

创建子图

你可以通过plt.figure创建一张新的图,plt.subplot来创建子图。subplot()指令包含numrows(行数), numcols(列数), fignum(图像编号),其中图像编号的范围是从1到行数 * 列数。在行数 * 列数<10时,数字间的逗号可以省略。

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

你可以多次使用figure命令来产生多个图,其中,图片号按顺序增加。这里,要注意一个概念当前图和当前坐标。所有绘图操作仅对当前图和当前坐标有效。通常,你并不需要考虑这些事,下面的这个例子为大家演示这一细节。

plt.figure(1)                # 第一张图
plt.subplot(211)             # 第一张图中的第一张子图
plt.plot([1,2,3])
plt.subplot(212)             # 第一张图中的第二张子图
plt.plot([4,5,6])


plt.figure(2)                # 第二张图
plt.plot([4,5,6])            # 默认创建子图subplot(111)

plt.figure(1)                # 切换到figure 1 ; 子图subplot(212)仍旧是当前图
plt.subplot(211)             # 令子图subplot(211)成为figure1的当前图
plt.title('Easy as 1,2,3')   # 添加subplot 211 的标题

添加文字

text()可以在图中的任意位置添加文字,并支持LaTex语法
xlable(), ylable()用于添加x轴和y轴标签
title()用于添加图的题目

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# 数据的直方图
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
#添加标题
plt.title('Histogram of IQ')
#添加文字
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

t0 = plt.text(0.35,0.5,'my text')
plt.setp(t0, color='b',fontsize=24)
t = plt.xlabel('my data', fontsize=14, color='red')

注释文本

在数据可视化的过程中,图片中的文字经常被用来注释图中的一些特征。使用annotate()方法可以很方便地添加此类注释。在使用annotate时,要考虑两个点的坐标:被注释的地方xy(x, y)和插入文本的地方xytext(x, y)

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )

plt.ylim(-2,2)
plt.show()

图例

一个图例包含多个图例项,每个图例项由图例说明和图例标签构成
图例标签
由彩色的图案构成,位于图例说明的左侧
图例说明
图例标签的说明文字
使用legend()函数可以自动添加图例

line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend(handles=[line_up, line_down])

有时候多个图例图例分别添加在不同位置使图有更强的可读性。可以通过多次调用legned()函数来实现。添加图例的位置可以用关键词loc来指定。

line1, = plt.plot([1,2,3], label="Line 1", linestyle='--')
line2, = plt.plot([3,2,1], label="Line 2", linewidth=4)

# Create a legend for the first line.
first_legend = plt.legend(handles=[line1], loc=1)

# Add the legend manually to the current Axes.
ax = plt.gca().add_artist(first_legend)

# Create another legend for the second line.
plt.legend(handles=[line2], loc=4)

plt.show()

seaborn介绍

参考以下链接:http://seaborn.pydata.org/tutorial.html

格式设置 Style management

seaborn有五种模版darkgrid, whitegrid, dark, white, and ticks可以选择

sns.set_style("whitegrid")
data = np.random.normal(size=(20, 6)) + np.arange(6) / 2
sns.boxplot(data=data);

可以用下面的命令去掉axes spines

sns.despine()

you can pass a dictionary of parameters to the rc argument of axes_style() and set_style()

sns.set_style("darkgrid", {"axes.facecolor": ".9"})
sinplot()

颜色设置
这里喜欢用的颜色:

渐变蓝色:
sns.palplot(sns.color_palette("Blues"))
渐变绿色:
sns.palplot(sns.color_palette("BuGn_r"))
渐变紫色:
sns.palplot(sns.cubehelix_palette(8))

颜色设置方法:

x, y = np.random.multivariate_normal([0, 0], [[1, -.5], [-.5, 1]], size=300).T
cmap = sns.cubehelix_palette(light=1, as_cmap=True)
sns.kdeplot(x, y, cmap=cmap, shade=True);

设置图像的大小和位置

f, ax = plt.subplots(figsize=(7, 3))
sns.countplot(y="deck", data=titanic, color="c");

各类图像

分布图

单变量分布图

在画分布图的时候可以选择是否加阴影(就是下面的填充),可以选择是否按照什么分布fit,可以选择kde和hist

sns.distplot(x, bins=20, kde=False, rug=True,hist=False);
sns.kdeplot(x, bw=.2, label="bw: 0.2",shade=True, cut=0);
sns.distplot(x, kde=False, fit=stats.gamma);
两个变量关系图

从最简单的散点图开始:

sns.jointplot(x="x", y="y", data=df);

难一点的蜂窝图
x, y = np.random.multivariate_normal(mean, cov, 1000).T
with sns.axes_style("white"):
    sns.jointplot(x=x, y=y, kind="hex", color="k");
以及密度核型图
sns.jointplot(x="x", y="y", data=df, kind="kde");

等高线图:

f, ax = plt.subplots(figsize=(6, 6))
sns.kdeplot(df.x, df.y, ax=ax)
sns.rugplot(df.x, color="g", ax=ax)
sns.rugplot(df.y, vertical=True, ax=ax);

还可以玩出花样:

g = sns.jointplot(x="x", y="y", data=df, kind="kde", color="m")
g.plot_joint(plt.scatter, c="w", s=30, linewidth=1, marker="+")
g.ax_joint.collections[0].set_alpha(0)
g.set_axis_labels("$X$", "$Y$");

pairplot

iris = sns.load_dataset("iris")
sns.pairplot(iris);

g = sns.PairGrid(iris)
g.map_diag(sns.kdeplot)
g.map_offdiag(sns.kdeplot, cmap="Blues_d", n_levels=6);

类别变量

sns.stripplot(x="day", y="total_bill", data=tips);
sns.swarmplot(x="day", y="total_bill", data=tips);
sns.swarmplot(x="total_bill", y="day", hue="time", data=tips);
sns.boxplot(x="day", y="total_bill", hue="time", data=tips);
sns.violinplot(x="total_bill", y="day", hue="time", data=tips);

可以将两个图叠加在一起

sns.violinplot(x="day", y="total_bill", data=tips, inner=None)
sns.swarmplot(x="day", y="total_bill", data=tips, color="w", alpha=.5);

对于图进行基本的统计:

sns.barplot(x="sex", y="survived", hue="class", data=titanic);
sns.countplot(x="deck", data=titanic, palette="Greens_d");
sns.pointplot(x="sex", y="survived", hue="class", data=titanic);

分面图:

sns.factorplot(x="day", y="total_bill", hue="smoker",
               col="time", data=tips, kind="swarm");

线性关系图

sns.regplot(x="total_bill", y="tip", data=tips);
sns.lmplot(x="total_bill", y="tip", data=tips);
上一篇下一篇

猜你喜欢

热点阅读