python绘图教程_Python绘图教程

python绘图教程

Plotly (Plot.ly as its URL goes), is a tech-computing company based in Montreal. It is known for developing and providing online analytics, statistics and graphing tools for individuals or companies. It also develops/provides scientific graphing libraries for Arduino, Julia, MATLAB, Perl, Python, R and REST.

Plotly( 网址Plot.ly )是一家位于蒙特利尔的技术计算公司。 它以为个人或公司开发和提供在线分析,统计和绘图工具而闻名。 它还为Arduino,Julia,MATLAB,Perl,Python,R和REST开发/提供科学图形库。

Python Plotly库 (Python Plotly Library)

Plotly’s Python graphing library makes interactive graphs online and allows us to save them offline if need be.

Plotly的Python图形库可在线生成交互式图形,并允许我们根据需要将其离线保存。

为什么情节 (Why Plotly)

Plotly has got some amazing features that make it better than other graphing libraries:

Plotly具有一些惊人的功能,使其比其他图形库更好:

  • It is interactive by default

    默认情况下是交互式的
  • Charts are not saved as images but serialized as JSON, making them open to be read with R, MATLAB, Julia and others easily

    图表不保存为图像,而是序列化为JSON,使其易于使用R,MATLAB,Julia等读取
  • Exports vector for print/publication

    导出矢量以进行打印/发布
  • Easy to manipulate/embed on web

    易于操作/嵌入网络

入门 (Getting Started)

We need PIP (python package installer) to get working with plotly, we’ll also need to create an account with plotly in case we want to use the online facilities. For this lesson, we’ll stick to offline usage only.

我们需要PIP (python软件包安装程序)才能开始使用plotly,还需要使用plotly创建一个帐户,以防我们想使用在线工具。 在本课程中,我们将仅坚持离线使用。

安装 (Installation)

To install plotly, open a terminal window and run the following command:

要以图形方式安装,请打开一个终端窗口并运行以下命令:

sudo pip install plotly

This may take a few minutes to install to collect dependencies and download them:

install python plotly library

安装可能需要几分钟来收集依赖关系并下载它们:

剧情地使用 (Using Plotly)

To use plotly in any of the Python scripts, we will need to import plotly as:

要在任何Python脚本中使用plotly,我们需要将plotly导入为:

import plotly

A few more steps and you are ready to use plotly. For Online usage, you need to set up credentials. This can be done as:

再执行几步,您就可以开始使用了。 对于在线使用,您需要设置凭据。 这可以通过以下方式完成:

plotly.tools.set_credentials_file(username='YourUsernameHere', api_key='YourAPIkeyHere')

For offline usage, we need to call plot like the following for offline usage:

对于脱机使用,我们需要调用如下图来进行脱机使用:

plotly.offline.plot()

测试安装 (Test Installation)

Before we can start using plotly, let’s test its installation with an easy script:

在开始使用plotly之前,让我们使用一个简单的脚本测试其安装:

import plotly
print(plotly.__version__)

Let’s see the output for this program:

python plotly version

As expected, this returns the latest version of plotly.

让我们看一下该程序的输出:

如预期的那样,这将返回plotly的最新版本。

制作简单图形 (Making a Simple Graph)

Let’s start with a simple “Hello, World” program with a sample code snippet:

让我们从一个带有示例代码片段的简单“ Hello,World”程序开始:

import plotly
from plotly.graph_objs import Scatter, Layout

plotly.offline.plot({
    "data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
    "layout": Layout(title="hello world")
})

Let’s see the output for this program:

plotly simple graph example

As cleary visible, this graph is saved as an HTML file in the same directory as the script.

让我们看一下该程序的输出:

清晰可见,该图以HTML文件格式保存在脚本所在的目录中。

基本图表 (Basic Charts)

To start visualising data, we will start with Basic Charts using Plotly and then move to more complex examples which shows time-related plotting.

为了开始可视化数据,我们将从使用Plotly的基本图表开始,然后转到显示与时间有关的绘图的更复杂的示例。

散点图 (Scatter Plot)

We’ll create a basic chart based on some random data using numpy. If numpy isn’t installed on your machine, install it using this command:

我们将使用numpy根据一些随机数据创建一个基本图表。 如果您的计算机上未安装numpy,请使用以下命令进行安装:

pip install numpy

Here is a sample program to show a scatter plot:

这是显示散点图的示例程序:

import plotly
import plotly.graph_objs as go

# Create random data with numpy
import numpy as np

N = 1000
random_x = np.random.randn(N)
random_y = np.random.randn(N)

# Create a trace
trace = go.Scatter(
    x = random_x,
    y = random_y,
    mode = 'markers'
)
data = [trace]

# Plot and embed in ipython notebook!
plotly.offline.plot(data, filename='basic-scatter')

Let’s see the output for this program:

plotly scatter plot

In this script, we also provided a name for the HTML file.

让我们看一下该程序的输出:

在此脚本中,我们还提供了HTML文件的名称。

线和散点图 (Line and Scatter Plot)

We can create some more sophisticated/ informative plots such as Line Scatter plot in a similar manner as above:

我们可以按照上面类似的方式来创建一些更复杂/更有用的图,例如线散布图:

import plotly
import plotly.graph_objs as go

# Create random data with numpy
import numpy as np

N = 100
random_x = np.linspace(0, 1, N)
random_y0 = np.random.randn(N)+5
random_y1 = np.random.randn(N)
random_y2 = np.random.randn(N)-5

# Create traces
trace0 = go.Scatter(
    x = random_x,
    y = random_y0,
    mode = 'markers',
    name = 'markers'
)

trace1 = go.Scatter(
    x = random_x,
    y = random_y1,
    mode = 'lines+markers',
    name = 'lines+markers'
)

trace2 = go.Scatter(
    x = random_x,
    y = random_y2,
    mode = 'lines',
    name = 'lines'
)

data = [trace0, trace1, trace2]
plotly.offline.plot(data, filename='scatter-mode')

Let’s see the output for this program:

plotly line and scatter plot example

This is not it. This graph is much more informative than it looks right now. Move the mouse pointer to any of the plotted point and you’ll see more information about that point:

让我们看一下该程序的输出:

绘制线和散点图示例

不是吗 该图比现在看起来具有更多的信息。 将鼠标指针移到任意绘制的点,您将看到有关该点的更多信息:

箱形图 (Box Plots)

Box Plots are quite informative and helpful especially when you have too much to show from very little data. Let’s try and create one:

箱形图非常有用,特别是当您需要从很少的数据中显示太多内容时。 让我们尝试创建一个:

import random
import plotly
from numpy import *

N = 30.     # Number of boxes

# generate an array of rainbow colors by fixing the saturation and lightness of the HSL representation of colour
# and marching around the hue.
c = ['hsl('+str(h)+',50%'+',50%)' for h in linspace(0, 360, N)]

# Each box is represented by a dict that contains the data, the type,
# and the colour.
# Use list comprehension to describe N boxes, each with a different colour and
# with different randomly generated data:
data = [{
    'y': 3.5*sin(pi * i/N) + i/N+(1.5+0.5*cos(pi*i/N))*random.rand(10),
    'type':'box',
    'marker':{'color': c[i]}
    } for i in range(int(N))]

# format the layout
layout = {'xaxis': {'showgrid':False,'zeroline':False, 'tickangle':60,'showticklabels':False},
          'yaxis': {'zeroline':False,'gridcolor':'white'},
          'paper_bgcolor': 'rgb(233,233,233)',
          'plot_bgcolor': 'rgb(233,233,233)',
          }

plotly.offline.plot(data)

Let’s see the output for this program:

plotly box plot example

Again, we moved the mouse point to one of the point to explore more information about that point.

让我们看一下该程序的输出:

同样,我们将鼠标指针移至该指针之一,以探索有关该指针的更多信息。

等高线图 (Contour Plots)

Contour Plots are one of most commonly used scientific plots:

轮廓图是最常用的科学图之一:

from plotly import tools
import plotly
import plotly.graph_objs as go

trace0 = go.Contour(
    z=[[2, 4, 7, 12, 13, 14, 15, 16],
       [3, 1, 6, 11, 12, 13, 16, 17],
       [4, 2, 7, 7, 11, 14, 17, 18],
       [5, 3, 8, 8, 13, 15, 18, 19],
       [7, 4, 10, 9, 16, 18, 20, 19],
       [9, 10, 5, 27, 23, 21, 21, 21],
       [11, 14, 17, 26, 25, 24, 23, 22]],
    line=dict(smoothing=0),
)

trace1 = go.Contour(
    z=[[2, 4, 7, 12, 13, 14, 15, 16],
       [3, 1, 6, 11, 12, 13, 16, 17],
       [4, 2, 7, 7, 11, 14, 17, 18],
       [5, 3, 8, 8, 13, 15, 18, 19],
       [7, 4, 10, 9, 16, 18, 20, 19],
       [9, 10, 5, 27, 23, 21, 21, 21],
       [11, 14, 17, 26, 25, 24, 23, 22]],
    line=dict(smoothing=0.85),
)

data = tools.make_subplots(rows=1, cols=2,
                          subplot_titles=('Without Smoothing', 'With Smoothing'))

data.append_trace(trace0, 1, 1)
data.append_trace(trace1, 1, 2)

plotly.offline.plot(data)

Let’s see the output for this program:

plotly contour plot

These kind of plots are used a lot while showing heat map data.

让我们看一下该程序的输出:

这些图在显示热图数据时经常使用。

财务图表 (Financial Charts)

Financial Charts are mycg more complex to read but are easy to make with Plotly. Let;s see some types of the charts taht can be made with Plotly.

金融图表的mycg阅读起来比较复杂,但使用Plotly可以轻松制作。 让我们看一下可以用Plotly制作的某些类型的图表。

时间序列图 (Time Series Plot)

Let’s start with a Time Series Plot. We will make use of sample data by Plotly itself which served by Github Repository. Here is a sample program:

让我们从时间序列图开始。 我们将利用Github存储库提供的Plotly本身的示例数据。 这是一个示例程序:

import plotly
import plotly.graph_objs as go
import pandas as pd

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")

data = [go.Scatter(
          x=df.Date,
          y=df['AAPL.Close'])]

plotly.offline.plot(data)

Let’s see the output for this program:

plotly timeseries plot

If pandas isn’t installed on your machine, install it using this command:

让我们看一下该程序的输出:

如果您的计算机上未安装pandas ,请使用以下命令进行安装:

pip install pandas

OHLC图表 (OHLC Chart)

OHLC Charts are also an excellent way to explain time-series related data for non-uniform distribution. Let’s look at a code snippet:

OHLC图表还是解释非均匀分布的时间序列相关数据的绝佳方法。 让我们看一下代码片段:

import plotly
import plotly.graph_objs as go
from datetime import datetime

open_data = [33.0, 33.3, 33.5, 33.0, 34.1]
high_data = [33.1, 33.3, 33.6, 33.2, 34.8]
low_data = [32.7, 32.7, 32.8, 32.6, 32.8]
close_data = [33.0, 32.9, 33.3, 33.1, 33.1]

dates = [datetime(year=2013, month=10, day=10),
         datetime(year=2013, month=11, day=10),
         datetime(year=2013, month=12, day=10),
         datetime(year=2014, month=1, day=10),
         datetime(year=2014, month=2, day=10)]

trace = go.Ohlc(x=dates,
                open=open_data,
                high=high_data,
                low=low_data,
                close=close_data)
data = [trace]

plotly.offline.plot(data, filename='ohlc_datetime')

Let’s see the output for this program:

plotly OHLC plot

让我们看一下该程序的输出:

结论 (Conclusion)

In this lesson, we studied another excellent Python library which is used for visualisation and offline usage.

在本课程中,我们研究了另一个出色的Python库,该库用于可视化和离线使用。

Read more Machine Learning posts here.

在此处阅读更多机器学习文章。

翻译自: https://www.journaldev.com/19692/python-plotly-tutorial

python绘图教程