pyhton matlibplot 绘制三维柱状图

# -*- coding: utf-8 -*-
"""
Created on 11th Feb 24 10:58:13 2018

@author: biggermax
"""

from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm,colors
import matplotlib as mpl
from sklearn import preprocessing


zmin = 0.85
zmax = 0.90


def useLargeSize(axis,marker_lines = None, fontsize = 'xx-large',fontproperties=None):
    '''
      将X,Y坐标轴的标签、刻度以及legend都使用大字体,
      所有线条采用粗线
    '''
    axis.xaxis.get_label().set_size(fontsize)
    axis.yaxis.get_label().set_size(fontsize)
    #分别设置x轴和y轴上刻度值的字体大小
    for label in axis.xaxis.get_ticklabels():
        label.set_fontsize(14)
    for label in axis.yaxis.get_ticklabels():
        label.set_fontsize(14)
    # 设置线的粗细
    LW = 2.3
    for line in axis.get_lines():
        line.set_lw( LW )
    leg = axis.get_legend()
    if(leg):
        ltext  = leg.get_texts()  # all the text.Text instance in the legend
        if(fontproperties):
            plt.setp(ltext, fontproperties=fontproperties)
        plt.setp(ltext, fontsize='x-large')
        llines = leg.get_lines()  # all the lines.Line2D instance in the legend
        plt.setp(llines,linewidth= LW )
        if(marker_lines and len(marker_lines)>=len(llines)):
            for i in range(0,len(llines)):
                plt.setp(llines[i],
                    marker = marker_lines[i].get_marker(),
                    markeredgecolor= marker_lines[i].get_markeredgecolor(),\
                    markerfacecolor= marker_lines[i].get_markerfacecolor(),\
                    markeredgewidth= marker_lines[i].get_markeredgewidth(),
                    markersize= marker_lines[i].get_markersize() )
def readData(rstr):#获取X,Y,Z数据
    M = []
    items = rstr.strip('\n').split('\t')
    for i in range(1,len(items)):
        M.append(float(items[i]))
    return np.array(M)
def MinMaxSc(z):#将Z的值映射到Z轴刻度上
    npz = np.array(z)
    lz = []
    for n in npz:
        lz.append((n - zmin)/(zmax - zmin))
    return np.array(lz)


def float2color(zero2one):#根据归一化后Z值大小(0到1之间),将Z 值转换为彩虹色
    x = int(zero2one * 255 % 256)
    r = cm.jet(x)[0] 
    g = cm.jet(x)[1]
    b = cm.jet(x)[2]
    return (r,g,b)


def Detectionplot():#3D柱状图绘制


    # data = sio.loadmat('F:\detection.mat')    #完成数据的导入
    # m = data['data']  #将其与m数组形成对应关系

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')   #此处因为是要和其他的图像一起展示,用的add_subplot,如果只是展示一幅图的话,可以用subplot即可
    X = []
    Y = []
    Z = []
    f = open('pic_data.csv','r',encoding = 'utf-8')
    for row,i in zip(f,range(3)):
        if i == 0:
            Z = readData(row)
        if i == 1:
            X = readData(row)
        if i == 2:
            Y = readData(row)

    f.close()
    x = X
    y = Y
    z = Z

    x = x.flatten('F')   #flatten功能具体可从Declaration中看到
    y = y.flatten('F')

#更改柱形图的颜色
    C = [] 
    mmp = preprocessing.MinMaxScaler(feature_range=(0,1), copy=True)  
    mmpc = mmp.fit_transform(np.array(z)) 
    for a in mmpc:
        C.append(float2color(a))

#此处dx,dy,dz是决定在3D柱形图中的柱形的长宽高三个变量
    dx = 0.035 * np.ones_like(x)
    dy = 0.035 * np.ones_like(y)
    dz = MinMaxSc(z)
    dz = np.array(dz).flatten()
    z = np.zeros_like(dz)

#设置三个维度的标签
    ax.set_xlabel('ρ',fontsize='x-large')
    ax.set_ylabel('τ',fontsize='x-large')
    ax.set_zlabel('Micro-F1',fontsize='x-large')
    
    ax.set_xlim(0.05,0.95)
    ax.set_ylim(0.05,0.95)
    ax.set_zticks(np.linspace(0,1,6))  
    ax.set_zticklabels( ('0.80','0.82', '0.84', '0.86', '0.88', '0.90'),fontsize='x-large')
    # ax.set_zticks(list([0.85,0.875,0.90,0.925,0.95]))
    # ax.set_zlim(0.85,0.9)
    useLargeSize(ax)
    ax.bar3d(x, y, z, dx, dy, dz,color = C,  zsort='average')

    plt.show()

Detectionplot()

你可能感兴趣的:(新手上路)