一、目标

以csv文件中的Kshell列值为Y轴,Degree列值为Y轴,分别以Upper列、EquUpper列、EquLower列,Lower列这四列的值为第三维,在对应的X、Y坐标上以颜色的深浅表示值的大小,得到四个结果。部分文件格式如下:

达到效果:

二、实现步骤

1、环境配置

在环境配置上花费了很长时间,主要是在PyDev中使用matplotlib包中的cm时,无法识别它的属性,解决方法:

(1)jdk、python、matplotlib等有32位、64位区分的,统一使用相同的位数版本。这里使用的64位,Python为2.7,这里使用的python安装包和模块安装包下载地址http://download.csdn.net/detail/suncherrydream/9840726

首先安装Python,直接下一步即可,这里安装路径为C:\Python27

接下来安装其他模块,首先确定这些模块放置的位置,这里放在了C:\Python27\Scripts下(不用非放在这里,只是举个例子)

然后利用Python自带的pip进行安装,如果没有为安装的python配置环境变量,需要在命令行环境下,先进入C:\Python27\Scripts目录下,然后输入pip install 包文件名进行安装,第一次使用时可能提示有更新的pip版本,将提示内容输入命令行即可。如下图所示:

(2)在Eclips中使用PyDev,并设置解释器(interpreter)为刚刚安装的python

方法参照  http://blog.csdn.net/yanzi1225627/article/details/19575437

安装完成并添加完解释器后即可以创建自己的python项目,创建时候选择PyDev Project,下一步时候可以选择已经添加的解释器,因为你可能同时安装了python2.7和python35,并将两个版本的解释器都添加到了PyDev中,这样可以通过这里来设置你希望使用哪个版本的Python解释器来解析你的代码

创建项目完成后,即可创建自己的包(pacakge),并在包下创建自己的模块(也可以不创建包)

(2)在完成上面的环境搭建工作后,在新创建的模块中输入下面语句的时候,

from matplotlib import cm

cmap=cm.Blues

在第二行依然提示Undefined variable from import,,即无法识别cm后面的Blues,做法如下图所示,强加了matplotlib,至此我的问题得到了解决

2、代码实现

(1)读取数据到内存中,每列放在一个数组中,几个数组中相同下标对应数据是csv文件中同一行的数据。实现方法为readData()

(2)获取X轴和Y轴刻度数组大小,这里让kshell列为Y轴,degree为X轴,数组的长度与对应轴的最大值相同,以kshell为例,kshell列中的最大值为8,则kshell对应轴的刻度数组为[1,2,3,4,5,6,7,8](此不没有生成数组,仅得到数组大小,生成数组在第(4)步中完成)。实现方法为getSize(),返回两个值,分别表示degree列的最大值,kshell列的最大值max_degree, max_kshell

(3)根据前面读取的数据生成z轴数据,实际上开始展现的就是三维数据的结果,无非将Z轴去掉,Z轴对应值在X轴、Y轴对应的位置上用颜色的深浅表示,实现方法为generateZ(max_degree, max_kshell),返回结果为z_upper_values, z_eu_values, z_el_values, z_lower_values,这四个结果均为二位数组,如z_upper_values[1][2]的值为value表示对于upper数据,在坐标x=2,y=1的位置的值为value。

(4)根据上面获取的x轴y轴刻度数组大小生成对应的数组,值得注意的是对于Y轴,数组中下标为0的值将会放在Y轴的最顶端,所以如果想按我们正常的随着Y轴正向值变大,需要将Y轴对应的数组按照倒序存放

i = 1
while(i <= int(max_degree)):  # the value at index0 is the min value
x_degrees.append(int(i))
i += 1
j = int(max_kshell)
while(j > 0):  # the value at index0 is the max value
y_kshells.append(int(j))
j -= 1

(5)绘制并保存结果,实现方法为draw_heatmap(data0, xlabels, ylabels, savepath, titleStr),参数以为(3)中获得的z轴数据对应的二维数组,xlabels,ylabels分别为(4)中获得的X轴和Y轴数组,savepath为将得到的结果保存的位置,titleStr是为坐标系设置的含义。

完整实现代码如下:

'''
Created on 20170511
@author: Cherry
'''
import csv
from matplotlib import cm
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import FormatStrFormatter
from matplotlib.pyplot import savefig
degrees = []
kshells = []
upper_values = []
eu_values = []
el_values = []
lower_values = []
root = 'D:/Cherry/data/netsci'
dataPath = root + '/result_f_distribution.csv'
def readData():
with open(dataPath, 'r') as f:
i = 0
for row in csv.reader(f.read().splitlines()):
if i == 0:
i += 1
else:
id, kshell, degree, upper, eu, el, lower = [i for i in row]
degrees.append(degree)
kshells.append(kshell)
upper_values.append(upper)
eu_values.append(eu)
el_values.append(el)
lower_values.append(lower)
def getSize():
max_degree = 0
max_kshell = 0
for degree in degrees:
if max_degree < int(degree):
max_degree = int(degree)
for kshell in kshells:
if max_kshell < kshell:
max_kshell = kshell
return max_degree, max_kshell
def generateZ(max_degree, max_kshell):
max_degree = int(max_degree)
max_kshell = int(max_kshell)
z_upper_values = [None] * max_kshell
z_eu_values = [None] * max_kshell
z_el_values = [None] * max_kshell
z_lower_values = [None] * max_kshell
for i in range(len(z_upper_values)):
z_upper_values[i] = [0] * max_degree
z_eu_values[i] = [0] * max_degree
z_el_values[i] = [0] * max_degree
z_lower_values[i] = [0] * max_degree
for j in range(len(degrees)):
index_x = degrees[j]  # get the degree named index_x, then regard the index_x-1 as the zvalue[][]'s second dimention index.   zvalue[][index-x-1]
index_y = kshells[j]  # get the kshell named index_y, then regard the max-kshell-index_y as the zvalue[][]'s first dimention index.  zvalue[max_kshell][]
upperValue = upper_values[j]
z_upper_values[int(max_kshell) - int(index_y)][int(index_x) - 1] = float(upperValue)
euValue = eu_values[j]
z_eu_values[int(max_kshell) - int(index_y)][int(index_x) - 1] = float(euValue)
elValue = el_values[j]
z_el_values[int(max_kshell) - int(index_y)][int(index_x) - 1] = float(elValue)
lowerValue = lower_values[j]
z_lower_values[int(max_kshell) - int(index_y)][int(index_x) - 1] = float(lowerValue)
return z_upper_values, z_eu_values, z_el_values, z_lower_values
def draw_heatmap(data0, xlabels, ylabels, savepath, titleStr):
cmap = cm.Blues
figure = plt.figure(facecolor='w')
# set the font
font = {'family' : 'serif', 'color'  : 'darkred', 'weight' : 'normal', 'size'   : 16, }
titlefont = {'family' : 'serif', 'color'  : 'black', 'weight' : 'normal', 'size'   : 20, }
ax = figure.add_subplot(1, 1, 1, position=[0.8, 0.15, 1, 1])
ax.set_yticks(range(len(ylabels)))
ax.set_yticklabels(ylabels)
ax.set_xticks(range(len(xlabels)))
ax.set_xticklabels(xlabels)
ax.set_ylabel('kshell', fontdict=font)  # set labelY to show the meaning of axiX
ax.set_xlabel('degree', fontdict=font)  # set labelX to show the meaning of axiY
plt.title(titleStr, fontdict=titlefont)  # set title to show the meaning of the distribution graph
xmajorLocator = MultipleLocator(5)  # set the main scale of axiX to the multiple of 5
xmajorFormatter = FormatStrFormatter('%u')  # set the famat of the labelX
#     xminorLocator   = MultipleLocator(5)
ax.xaxis.set_major_locator(xmajorLocator)
ax.xaxis.set_major_formatter(xmajorFormatter)
vmax = data0[0][0]
vmin = data0[0][0]
for i in data0:
for j in i:
if j > vmax:
vmax = j
if j < vmin:
vmin = j
map0 = ax.imshow(data0, interpolation='nearest', cmap=cmap, aspect='auto', vmin=vmin, vmax=vmax)
plt.colorbar(mappable=map0, cax=None, ax=None, shrink=0.5)
# plt.show()
savefig(savepath)
plt.clf()
readData()
max_degree, max_kshell = getSize()
z_upper_values, z_eu_values, z_el_values, z_lower_values = generateZ(max_degree, max_kshell)
x_degrees = []
y_kshells = []
i = 1
while(i <= int(max_degree)):  # the value at index0 is the min value
x_degrees.append(int(i))
i += 1
j = int(max_kshell)
while(j > 0):  # the value at index0 is the max value
y_kshells.append(int(j))
j -= 1
draw_heatmap(z_upper_values, x_degrees, y_kshells, root + '/distri_upper.png', 'upper')
draw_heatmap(z_eu_values, x_degrees, y_kshells, root + '/distri_eu.png', 'eu')
draw_heatmap(z_el_values, x_degrees, y_kshells, root + '/distri_el.png', 'el')
draw_heatmap(z_lower_values, x_degrees, y_kshells, root + '/distri_lower.png', 'lower')
print('finished')
参考文章地址:
matplotlib
包下载地址

Python绘制热图

Python中的Numpy、SciPy、MatPlotLib安装与配置
Undefined variable from import的解决方案
matplotlib绘图实例:pyplot、pylab模块及作图参数
Python之路—matplotlib与云图
使用matplotlib的示例:调整字体-设置刻度、坐标、colormap和colorbar等
[python数据自动化处理]python 用 matplotlib画图时设定x/y轴坐标主刻度及次要刻度的方法
python matplotlib绘图设置坐标轴刻度、文本
使用python中的matplotlib进行绘图分析数据
python中创建指定大小的多维数组
python的二维数组操作
Configure Interpreter
Python格式化字符串
Heatmaps in Python
python给scatter设置颜色渐变条colorbar

利用python的matplotlib绘制分布图相关推荐

  1. 利用 python numpy +matplotlib 绘制股票k线图

    一.python numpy + matplotlib 画股票k线图 # -- coding: utf-8 -- import requests import numpy as np from mat ...

  2. python 绘制k线图_利用python numpy+matplotlib绘制股票k线图的方法

    一.python numpy + matplotlib 画股票k线图 # -- coding: utf-8 -- import requests import numpy as np from mat ...

  3. python如何画出多个独立的图片_在Python中用Matplotlib绘制多个图形并组合显示,利用,多图,合并,展示...

    有个需求就是利用Matplotlib画几个像模像样的统计图然后合并在一张图中,因为此前很少用这方面的东西,所以折腾了不少时间,今天介绍一下. 1.subplot多合一 其实,利用python 的mat ...

  4. python动态演示数据gdp_利用Python制作中国GDP分布图和动态演示

    利用Python制作中国GDP分布图和动态演示 数据读取 ## 导入相关模块import pandas as pdimport geopandas as gpdimport numpy as np i ...

  5. 利用Python制作中国GDP分布图和动态演示

    利用Python制作中国GDP分布图和动态演示 数据读取 ## 导入相关模块 import pandas as pd import geopandas as gpd import numpy as n ...

  6. python画矩阵热图_如何用python的matplotlib绘制热图

    python使用matplotlib绘制热图 python常用的绘图库就是matplotlib,今天在给公司绘图时,偶然间发现matplotlib可以绘制热图,并且十分简洁,拿出来跟大家分享一下.(由 ...

  7. python使用matplotlib绘制一条正弦曲线(plot函数可视化sine plot)

    python使用matplotlib绘制一条正弦曲线(plot函数可视化sine plot) 目录 python使用matplotlib绘制一条正弦曲线(plot函数可视化sine plot) #导入 ...

  8. Python使用matplotlib绘制透明背景的可视化图像并保存透明背景的可视化结果(transparent background)

    Python使用matplotlib绘制透明背景的可视化图像并保存透明背景的可视化结果(transparent background) 目录

  9. Python使用matplotlib绘制分组对比柱状图(bar plot)可视化时汉语(中文)标签显示成了框框□□、什么情况、我们有解决方案

    Python使用matplotlib绘制分组对比柱状图可视化时(bar plot)汉语(中文)标签显示成了框框□□.什么情况.我们有解决方案 目录

最新文章

  1. fzyzojP3372 -- [校内训练20171124]博弈问题
  2. 罗定中学2021年高考成绩查询,2020年罗定市各中学高考喜报!罗定中学、廷锴纪念、罗定实验均创历史...
  3. 合法的python变量名import_python 环境变量和import模块导入方法(详解)
  4. javascript小游戏_javaScript小游戏——网页版别踩白块
  5. .net excel循环插数据_科普:1根、2根、4根内存条插在主板内存插槽的位置
  6. Python maximum recursion depth exceeded while calling a Python object (gevent的SSL无限递归错误)的问题解决
  7. mysql内部参数是什么意思_mysql参数及解释
  8. lamda 对比两个list_正式支持多线程!Redis 6.0与老版性能对比评测
  9. 一条mysql语句判断是添加还是修改
  10. 修改Launcher2欢迎页面字符重叠
  11. 开始我们的Snippets!
  12. Rust Async: Pin概念解析
  13. Tomcat实现Web Socket
  14. 推荐几款程序员值得拥有的写文档工具
  15. Uni-app API
  16. YY语音无有效验证导致下载执行任意程序
  17. matlab-colormap-contourf函数
  18. 可以度量金融泡沫的对数周期幂律
  19. C++ 面试宝典 - 知识点集锦
  20. 初识openmeetings-db

热门文章

  1. XDM2020 Java版类似IDM微软下载器的开源下载工具编译
  2. tensorflow 学习(一)- 搭建一个三层的神经网络
  3. IDEA与GitHub的仓库相关联,幼儿园教学(狗头保命)
  4. 2018年2月Ivanti英万齐(前LANDESK蓝代斯克)关闭中国研发中心
  5. Java解析Excel文档,2003和2007版本不兼容问题
  6. 用计算机弹精灵宝可梦音乐,《精灵宝可梦》图鉴402:可以演奏出优美音乐的精灵——音箱蟀...
  7. 服装进销存管理软件哪个好用?看测评就知道了
  8. Photoshop教程8000例。平时想做的各种效果完整郎阔!
  9. S3C6410(OK6410开发板介绍)
  10. 统计学中几种简单的检验方式