search
HomeBackend DevelopmentPython Tutorial利用Python绘制MySQL数据图实现数据可视化

本教程的所有Python代码可以在网上的IPython notebook中获取。

考虑在公司里使用Plotly?可以看一下Plotly的on-premises企业版。(注:On-premises是指软件运行在工作场所或公司内部,详见维基百科)

注意操作系统:尽管Windows或Mac用户也可以跟随本文操作,但本文假定你使用的是Ubuntu系统(Ubuntu桌面版或Ubuntu服务器版)。如果你没有Ubuntu Server,你可以通过Amazon的Web服务建立一个云平台(阅读这份教程的前半部分)。如果你用的是Mac,我们推荐你购买并下载VMware Fusion,在上面安装Ubuntu桌面版。你也可以通过Zareason购买一台便宜的预装Ubuntu桌面版/服务器版的笔记本或服务器。

使用Python读取MySQL的数据并绘图很简单,所有你需要的工具都可以免费下载。本文会展示怎么做。如果你遇到问题或者卡住了,可以给feedback@plot.ly发送邮件,也可以在本文下面评论,或者在tweeter上@plotlygraphs。
第1步:确保MySQL已安装且在运行

首先,你需要有一台安装了MySQL的计算机或服务器。你可以通过以下方法检查MySQL是否安装:打开控制台,输入“mysql”,如果你收到MySQL无法连接的错误,这意味着MySQL安装了,但是没有运行。在命令行或“Terminal”中,尝试输入sudo /etc/init.d/mysql start并按回车来启动MySQL。

如果MySQL没有安装,不要失望。在Ubuntu中下载并安装只需一行命令:

shell> sudo apt-get install mysql-server --fix-missing

安装过程中会让你输入一个密码。安装结束后,你可以在终端中键入以下命令进入MySQL控制台:
 

shell> sudo mysql -uroot -p

输入“exit”就可以退出MySQL控制台,。

本教程使用MySQL经典的“world”样例数据库。如果你想跟随我们的步骤,可以在MySQL文档中心下载world数据库。你也可以在命令行中使用wget下载:
 

shell> wget http://downloads.mysql.com/docs/world.sql.zip

然后解压文件:
 

shell> unzip world.sql.zip

(如果unzip没有安装,输入sudo apt-get install unzip安装)

现在需要把world数据库导入到MySQL,启动MySQL控制台:
 

shell> sudo mysql -uroot -p

进入控制台后,通过以下MySQL命令使用world.sql文件创建world数据库:
 

mysql> CREATE DATABASE world;
mysql> USE world;
mysql> SOURCE /home/ubuntu/world.sql;

(在上面的SOURCE命令中,确保将路径改为你自己world.sql所在目录)。
上述操作说明摘自MySQL文档中心。
第2步:使用Python连接MySQL

使用Python连接MySQL很简单。关键得安装python的MySQLdb包。首先需要安装两项依赖:
 

shell> sudo apt-get install python-dev
shell> sudo apt-get install libmysqlclient-dev

然后安装Python的MySQLdb包:
 

shell> sudo pip install MySQL-python

现在,启动Python并导入MySQLdb。你可以在命令行或者IPython notebook中执行:
 

shell> python
>>> import MySQLdb

创建MySQL中world数据库的连接:
 

>>> conn = MySQLdb.connect(host="localhost", user="root", passwd="XXXX", db="world")

cursor是用来创建MySQL请求的对象。
 

>>> cursor = conn.cursor()

我们将在Country表中执行查询。
第3步:Python中执行MySQL查询

cursor对象使用MySQL查询字符串执行查询,返回一个包含多个元组的元组——每行对应一个元组。如果你刚接触MySQL语法和命令,在线的MySQL参考手册是一个很不错的学习资源。
 

>>> cursor.execute('select Name, Continent, Population, LifeExpectancy, GNP from Country');
>>> rows = cursor.fetchall()

rows,也就是查询的结果,是一个包含多个元组的元组,像下面这样:

2015330144147252.jpg (619×247)

使用Pandas的DataFrame来处理每一行要比使用一个包含元组的元组方便。下面的Python代码片段将所有行转化为DataFrame实例:
 

>>> import pandas as pd
>>> df = pd.DataFrame( [[ij for ij in i] for i in rows] )
>>> df.rename(columns={0: 'Name', 1: 'Continent', 2: 'Population', 3: 'LifeExpectancy', 4:'GNP'}, inplace=True);
>>> df = df.sort(['LifeExpectancy'], ascending=[1]);

完整的代码可以参见IPython notebook
第4步:使用Plotly绘制MySQL数据

现在,MySQL的数据存放在Pandas的DataFrame中,可以轻松地绘图。下面的代码用来绘制国家GNP(国民生产总值)VS平均寿命的图,鼠标悬停的点会显示国家名称。确保你已经下载了Plotly的Python库。如果没有,你可以参考一下它的入门指南。
 

import plotly.plotly as py
from plotly.graph_objs import *
 
trace1 = Scatter(
   x=df['LifeExpectancy'],
   y=df['GNP'],
   text=country_names,
   mode='markers'
)
layout = Layout(
   xaxis=XAxis( title='Life Expectancy' ),
   yaxis=YAxis( type='log', title='GNP' )
)
data = Data([trace1])
fig = Figure(data=data, layout=layout)
py.iplot(fig, filename='world GNP vs life expectancy')

完整的代码在这份IPython notebook中。下面是作为一个iframe嵌入的结果图:

2015330144839609.jpg (690×521)

利用Plotly的Python用户指南中的气泡图教程,我们可以用相同的MySQL数据绘制一幅气泡图,气泡大小表示人口的多少,气泡的颜色代表不同的大洲,鼠标悬停会显示国家名称。下面显示的是作为一个iframe嵌入的气泡图。

2015330144914465.jpg (690×497)

创建这个图表以及这个博客中的所有python代码都可以从这个IPython notebook中拷贝。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),