Ptyhon可视化:chapter3--绘制并定制化图表

来源:互联网 发布:各算法时间复杂度 编辑:程序博客网 时间:2024/06/03 21:28

一、定义图标类型---柱状图、线形图和堆积柱状图

   从matplotlib.pyplot库的一些常用图表入手

matplotlib中的基本图表包括一下元素:

  • x轴和y轴
  • x轴和y轴刻度
  • x轴和y轴刻度标签
  • 绘图区域

from matplotlib.pyplot import *x = [1, 2, 3, 4]y = [5, 4, 3, 2]figure()  # create figure# divide subplots into 2 x 3 grid# and select #1subplot(231)plot(x, y)subplot(232)bar(x, y)   #垂直柱状图subplot(233)barh(x, y)  #水平柱状图subplot(234)bar(x, y)# we need more data for stacked bar chartsy1 = [7, 8, 5, 3]bar(x, y1, bottom=y, color='r')   # 叠加柱状图subplot(235)  #箱线图boxplot(x)subplot(236)scatter(x, y)  #散点图show()
   subplot(231)把图表分割成2X3的网格,也也可以用subplot(3, 2, 1)

二、简单的正弦图和余弦图

import matplotlib.pyplot as pl import numpy as np x = np.linspace(-np.pi, np.pi, 256, endpoint=True)y = np.cos(x)y1 = np.sin(x)pl.plot(x, y)pl.plot(x, y1)pl.show()

三、设置坐标轴长度和范围

l = [-1, 1, -10, 10]    # xmin, xmax, ymin, ymax

axis(l)

添加新的坐标轴,可以调用matplotlib.pyplot.axes()方法。如果需要几个不同的视图来表达相同的数据的不同属性值,这就需要在一张图中组合显示多个图表

添加一条线,可以调用matplotlib.pyploty.axhline() or matplotlib.pyplot.axvline()

四、设置图表的线型、属性和格式化字符串

  一种常用的方式是: plot(x, y, linewidth=1.5)

       另一种

    lines = plot(x, y)

              setp(lines, 'linewidth', 1.5)

       用来改变线条的所有属性都包含在matplotlib.lines.Line2D累中





五、设置刻度、刻度标签和网络

   刻度定位器(tick locator) -- 指定刻度所在的位置

   刻度格式器(tick formatter) -- 指定刻度显示的样式

六、添加图例和注解

from matplotlib.pyplot import *import numpy as np x1 = np.random.normal(30, 3, 100)x2 = np.random.normal(20, 2, 100)x3 = np.random.normal(10, 3, 100)plot(x1, label='plot')plot(x2, label='2nd plot')plot(x3, label='last plot')#generate a legend boxlegend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=3, mode="expand", borderaxespad=0.)annotate("Important value", (55,20), xycoords='data', xytext=(5,38), arrowprops=dict(arrowstyle='->'))show()

七、移动轴线到图中央


八、绘制直方图

  matplotlib.pyploy.hist()来创建直方图

九、绘制误差条形图


十、绘制饼图


十一、绘制填充区域的图表


十二、绘制带彩色标记的散点图

import matplotlib.pyplot as plt import numpy as np x = np.random.randn(1000)y1 = np.random.randn(len(x))y2 = 1.2 + np.exp(x)ax1 = plt.subplot(121)plt.scatter(x, y1, color='indigo', alpha=0.3, edgecolors='white', label='no correl')plt.xlabel('no correlation')plt.grid(True)plt.legend()ax2 = plt.subplot(122, sharey=ax1, sharex=ax1)plt.scatter(x, y2, color='green', alpha=0.3, edgecolors='gray', label='correl')plt.xlabel('strong correlation')plt.grid(True)plt.legend()plt.show()

   



  



原创粉丝点击