您当前的位置: 首页 > 

宝哥大数据

暂无认证

  • 0浏览

    0关注

    1029博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

数据可视化

宝哥大数据 发布时间:2019-05-25 12:53:12 ,浏览量:0

   数据的可视化是数据探索、数据分析中的重要任务,通过可视化可以帮助我们发现数据的异常值、特征的分布情况等,为数据预处理提供重要支持。Spark目前对数据的可视化功能还很弱或还没有,不过没关系,我们可以借助Python或R等可视化功能,Python 和R在数据可视化方面功能很强大,这里以Python的数据可视化为例。Python的数据表现能力很强,其可视化可以使用matplotlib或plot等方法。matplotlib是一种比较低级但强大的绘图工具,可以进行很多定制化,但往往需要较大代码来实现; plot 是一种非常简洁的绘图工具,它主要基于pandas基础之上。

一、matplotlib
    plt.rcParams['font.sans-serif'] = ['SimHei']
    ###显示中文
    plt.rcParams['axes.unicode_minus'] = False  ## 防止坐标轴上的"-"号变为方块
    x = np.linspace(0, 10, 100)
    y = np.sin(x)
    y1 = np.cos(x)
    ##绘制一个图,长为10,宽为6(默认值是每个单位80像素)
    plt.figure(figsize=(10, 6))
    ###在图列中自动显示$间内容
    plt.plot(x, y, label="$sin(x)$", color="red", linewidth=2)
    plt.plot(x, y1, "b--", label="$cos(x^2)$")  ###b(blue),-- 线形
    plt.xlabel(u"X值")
    ##X坐标名称,u表示unicode编码
    plt.ylabel(u"Y值")
    plt.title(u"三角函数图像")
    ##t图名称
    plt.ylim(-1.2, 1.2)  ##y 上的max、min值
    plt.legend()
    ##显示图例
    plt.savefig('fig01.png')  ## 保持到当前目录
    plt.show()

在这里插入图片描述

matplotlib 官网上找图像组件说明图。通过这张图,我们对 matplotlib 整体地认识。

在这里插入图片描述

1.1、基本概念

参考: https://www.jianshu.com/p/78ba36dddad8

1.1.1、Figure

&emsp 图像窗口。Figure 是包裹 Axes、tiles、legends 等组件的最外层窗口。它其实是一个 Windows 应用窗口 。

1.1.2、Axes

  Axes 是轴域/子图。Axes 是带有数据的图像区域。从上文可知,它是位于 Figure 里面。那它和 Figure 是什么关系?这里可能文字难以表述清楚,我以图说文。用两图带你彻底弄清它们的关系。

    fig = plt.figure()                  # 创建一个没有axes的figure
    plt.title("No Axes on Figure")      # 设置标题

    plt.subplots(2, 2)                  # 创建一个2x2个axes的figure

    plt.show()                          # 展示

  根据运行结果图,我们不难看出。左图的 Figure1 中没有 axes,右图的 Figure2 中有 4 个 axes。因此,我们可以将 Axes 理解为面板,而面板是覆在窗口(Figure) 上。 在这里插入图片描述

1.1.3、坐标轴 (Axis)

  Axis 和 Axes 以及 Figure 这三者关系,你看完下图,会恍然大悟。 在这里插入图片描述

   x = np.arange(-5, 5, 0.5)
    y = 3 * x + 1
    y1 = x ** 2 + 5

    plt.figure()
    plt.plot(x, y, marker='o')
    plt.plot(x, y1, color='r', linestyle='--', marker='>')


    plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置显示中文
    plt.rcParams['axes.unicode_minus'] = False  ## 防止坐标轴上的"-"号变为方块

    # 设置坐标轴标签
    plt.xlabel("X 轴")
    plt.ylabel("Y 轴")

    # 限制x, y的范围
    # plt.xlim(-3, 5)
    # plt.ylim(0, 30)

    # 设置精准刻度
    # xticks() 和 yticks() 需要传入一个列表作为参数。
    # plt.xticks(np.arange(-5, 5, 1))
    # plt.yticks(np.arange(-20, 30, 5))

    # 该方法默认是将列表的值来设置刻度标签,
    # 如果你想重新设置刻度标签,则需要传入两个列表参数给 xticks() 和 yticks() 。
    # 第一个列表的值代表刻度,第二个列表的值代表刻度所显示的标签
    plt.xticks([-5, -3, 0, 3, 5],
               ['-5元', '-3元', 0, '3元', '5元' ])
    plt.yticks([-10, 0, 10, 20, 30],
               ['$-10db$', 0, '$10db$', '$20db$', '$30db$'])  # 使用$$ 将字符包含, 显示的更好看,


    plt.show()  # 展示

在这里插入图片描述

1.1.3.1、设置坐标轴的位置
    # Get the current ~matplotlib.axes.Axes instance on the current figure matching the given keyword args, or create one.
    ax = plt.gca()
    ax.spines['right'].set_color('none')        # 右边框消失
    ax.spines['top'].set_color('none')

    # x,y轴的刻度位置
    ax.xaxis.set_ticks_position("bottom")
    ax.yaxis.set_ticks_position("right")

    ax.spines['bottom'].set_position(('data', 0))   #指定 data  设置的bottom(也就是指定的x轴)绑定到y轴的0这个点上
    # ax.spines['left'].set_position(('data', 0))
	
	# 也可以使用axes参数
	# ax.spines['bottom'].set_position(('axes', 0.2))   #指定 data  设置的bottom(也就是指定的x轴)绑定到y轴的20%处

在这里插入图片描述

1.1.4、图例(Legend)
    plt.plot(x, y, marker='o', label='直线')
    plt.plot(x, y1, color='r', linestyle='--', marker='>', label='曲线')

    # 调用 plt.legend() 绘制出一个图例。plt.legend() 需要传入一个位置值
    plt.legend(loc='best')
    plt.show()  # 展示
loc的取值

在这里插入图片描述 在这里插入图片描述

1.1.5、标注(Annotation)

  有时某些数据点非常关键,需要突显出来。我们需要将该点绘制出来,即绘制散点图,再对其做注释。实现上述需求,我们要用到scatter()annotate()函数。scatter()是用于绘制散点图,这里我们只是用其来绘制单个点。scatter() 用法,后续文章会详细对其用法做说明。annotate()则是添加标注 。 scatter() 函数必须传入两个参数 x 和 y。值得注意得是,它们的数据类型是列表。x 代表要标注点的横轴位置,y 代表要标注点的横轴位置。x 和 y 列表中下标相同的数据是对应的。例如 x 为 [3, 4],y 为 [6, 8],这表示会绘制点(3,6),(4, 8)。因此,x 和 y 长度要一样。 annotate函数同样也有两个必传参数,一个是标注内容,另一个是 xy。标注内容是一个字符串。xy 表示要在哪个位置(点)显示标注内容。xy 位置地选定。一般是在scatter() 绘制点附近,但不建议重合,这样会影响美观。

    x = np.arange(-5, 5, 0.5)
    y1 = x ** 2 + 5

    fig = plt.figure()

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置显示中文
    plt.rcParams['axes.unicode_minus'] = False  ## 防止坐标轴上的"-"号变为方块

    # 设置坐标轴标签
    plt.xlabel("X 轴")
    plt.ylabel("Y 轴")

    # 设置精准刻度
    # xticks() 和 yticks() 需要传入一个列表作为参数。
    plt.xticks(np.arange(-5, 5, 1))
    plt.yticks(np.arange(-20, 30, 5))

    plt.plot(x, y1, color='r', label='曲线')

    # 调用 plt.legend() 绘制出一个图例。plt.legend() 需要传入一个位置值
    plt.legend(loc='best')

    x0 = 0
    y0 = x0 ** 2 + 5
    plt.scatter(x0, y0, s=50, color='b')
    plt.annotate('极小值点',
                 xy=(x0, y0),
                 xycoords='data',
                 xytext=(+10, +30),
                 textcoords='offset points',
                 arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2")
                 )

    # 如果你还想给点添加注释。这需要使用text()函数。text(x,y,s) 作用是在点(x,y) 上添加文本 s
    plt.text(-3.7, 25, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
         fontdict={'size': 16, 'color': 'r'})

    plt.show()  # 展示

在这里插入图片描述

1.1.6、tick
    x = np.linspace(-3, 3, 50)
    y = 0.1 * x

    plt.figure()
    plt.plot(x, y, linewidth=10, zorder=1)  # set zorder for ordering the plot in plt 2.0.2 or higher
    plt.ylim(-2, 2)
    ax = plt.gca()
    ax.spines['right'].set_color('none')
    ax.spines['top'].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))

    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontsize(12)
        # set zorder for ordering the plot in plt 2.0.2 or higher
        label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.8, zorder=2))
    plt.show()

在这里插入图片描述

1.2、散点图
# 散点图
def figureScatter():
    x = np.random.randn(1000)
    y = -x + np.random.randn(1000) * 0.5

    plt.scatter(x, y,
                s=30,
                c='g',
                marker='*',
                alpha=0.3  # 透明度
                )
    plt.show()

在这里插入图片描述

1.3、柱状图

def figureBar():
    n = 10
    x = np.arange(n)
    y1 = 3 * x + 1
    y2 = -2 * x - 1

    p1 = plt.bar(x, y1, color='r', width=0.8)
    p2 = plt.bar(x, y2, color='g', width=0.8)
    plt.xlabel("X")
    plt.ylabel("Y")
    plt.title("bar", fontsize="18")


    ax = plt.gca()
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position(('data', 0))

    for xt, yt in zip(x, y1):
        plt.text(xt, yt + 0.5,'%s' %yt, ha='center', va='bottom')

    for xt, yt in zip(x, y2):
        plt.text(xt, yt - 0.8,'%s' %yt, ha='center', va='top')

    plt.show()

在这里插入图片描述

1.4、Img

  热图(heatmap)是数据分析的常用方法,通过色差、亮度来展示数据的差异、易于理解。Python在Matplotlib库中,调用imshow()函数实现热图绘制。

    points = np.arange(-5, 5, 0.01)

    xs, ys = np.meshgrid(points, points)

    z = np.sqrt(xs ** 2 + ys ** 2)

    # 创建新的figure
    fig = plt.figure()

    # 绘制2x2两行两列共四个图,编号从1开始
    ax = fig.add_subplot(221)
    ax.imshow(z)

    ax = fig.add_subplot(222)
    # 使用自定义的colormap(灰度图)
    ax.imshow(z, cmap=plt.cm.gray)

    ax = fig.add_subplot(223)
    # 使用自定义的colormap
    ax.imshow(z, cmap=plt.cm.cool)

    ax = fig.add_subplot(224)
    # 使用自定义的colormap
    ax.imshow(z, cmap=plt.cm.hot)

    # 图片的显示
    plt.show()

在这里插入图片描述

1.4.1、使用imshow展示数据的相关性
def figureImg():
    # image data
    a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
                  0.365348418405, 0.439599930621, 0.525083754405,
                  0.423733120134, 0.525083754405, 0.651536351379]).reshape(3, 3)

    """
    for the value of "interpolation", check this:
    http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
    for the value of "origin"= ['upper', 'lower'], check this:
    http://matplotlib.org/examples/pylab_examples/image_origin.html
    """
    plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
    plt.colorbar(shrink=.92)

    plt.xticks(())
    plt.yticks(())
    plt.show()

在这里插入图片描述

关注
打赏
1587549273
查看更多评论
立即登录/注册

微信扫码登录

0.1630s