search
HomeBackend DevelopmentPython Tutorial详解在Python中调用ggplot的三种方法(图文)

本文提供了三种不同的方式在Python(IPython Notebook)中调用ggplot。

在大数据时代,数据可视化是一个非常热门的话题。各个BI的厂商无不在数据可视化领域里投入大量的精力。Tableau凭借其强大的数据可视化的功能成为硅谷炙手可热的上市公司。Tableau的数据可视化的产品,其理论基础其实是《The Grammar of Graphic》,该书提出了对信息可视化的图表的语法抽象体系,数据的探索和分析可以由图像的语法来驱动,而非有固定的图表类型来驱动,使得数据的探索过程变得友好而有趣。

然而对于The Grammar of Graphic的理论的实践,并非Tableau独占,ggplot作为R语言上得一个图形库,其理论基础也是这本书。(注,笔者曾就职的某BI巨头,主要职责也是数据可视化,我们曾经和加拿大团队研发过类似的产品,基于HTML5和D3,可惜由于种种原因未能推向市场)

现在越来越多的人开始使用python来做数据分析,IPython Notebook尤其令人喜爱,它的实时交互把脚本语言的优势发挥到极致。那么怎样才能在IPython Notebook中使用ggplot呢?我这里跟大家分享三种不同的方式供大家选择。
RPy2

第一种方式是使用rpy2, rpy2是对rpy的改写和重新设计,旨在提供Python用户在python中使用R的API

rpy2提供了对R语言的对象和方法的基本封装,当然也包括可视化的图库这一块。

下面就是一段运行ggplot的R程序使用rpy2在python中运行的例子:

from rpy2 import robjects
from rpy2.robjects import Formula, Environment
from rpy2.robjects.vectors import IntVector, FloatVector
from rpy2.robjects.lib import grid
from rpy2.robjects.packages import importr, data
import rpy2.robjects.lib.ggplot2 as ggplot2
 
# The R 'print' function
rprint = robjects.globalenv.get("print")
stats = importr('stats')
grdevices = importr('grDevices')
base = importr('base')
datasets = importr('datasets')
 
mtcars = data(datasets).fetch('mtcars')['mtcars']
 
pp = ggplot2.ggplot(mtcars) + \
   ggplot2.aes_string(x='wt', y='mpg', col='factor(cyl)') + \
   ggplot2.geom_point() + \
   ggplot2.geom_smooth(ggplot2.aes_string(group = 'cyl'),
             method = 'lm')
pp.plot()

以上程序在IPython Notebook中运行会有缺陷,会弹出一个新的窗口显示图,而且该python进程会阻塞在那里。我们希望图表能内嵌在IPython Notebook的页面中,为了解决该问题,我们引入如下代码:

%matplotlib inline
 
import uuid
from rpy2.robjects.packages import importr 
from IPython.core.display import Image
 
grdevices = importr('grDevices')
def ggplot_notebook(gg, width = 800, height = 600):
  fn = '{uuid}.png'.format(uuid = uuid.uuid4())
  grdevices.png(fn, width = width, height = height)
  gg.plot()
  grdevices.dev_off()
  return Image(filename=fn)

运行上述代码后,我们把ggplot的调用pp.plot()改为调用ggplot_notebook(pp, height=300)就能成功嵌入显示ggplot的结果。

201548145241359.png (800×300)

RMagic

另一种方式是使用rmagic,rmagicy实际上依赖于rpy2。它的使用方式更像是直接在使用R

%load_ext rmagic
library(ggplot2)
dat <- data.frame(x = rnorm(10), y = rnorm(10), 
         lab = sample(c(&#39;A&#39;, &#39;B&#39;), 10, replace = TRUE))
x <- ggplot(dat, aes(x = x, y = y, color = lab)) + geom_point()
print(x)

运行结果如下

201548145327917.png (480×480)

ggplot for python

ggplot是一个python的库,基本上是对R语言ggplot的功能移植到Python上。

运行安装脚本

pip install ggplot

安装成功后,可以试一下这个例子

%matplotlib inline
import pandas as pd
from ggplot import *
meat_lng = pd.melt(meat[[&#39;date&#39;, &#39;beef&#39;, &#39;pork&#39;, &#39;broilers&#39;]], id_vars=&#39;date&#39;)
ggplot(aes(x=&#39;date&#39;, y=&#39;value&#39;, colour=&#39;variable&#39;), data=meat_lng) + \
  geom_point() + \
  stat_smooth(color=&#39;red&#39;)

结果如下:

201548145402721.png (649×499)

总结

本文提供了三种不同的方式在Python(IPython Notebook)中调用ggplot。

rpy2和Rmagic都是一种对R的桥接,所以都需要安装R。不同之处在于rpy2提供Python接口而Rmagic更接近R。

ggplot Python库是ggplot的Python移植,所以无需安装R,部署起来更为简单,但功能上也许和R的ggplot还有差距。

大家可以根据自己的需要做出选择。

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 vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools