翻译完成

This commit is contained in:
MjSeven 2020-06-24 22:59:36 +08:00
parent d4c1c9cf96
commit 12dbd68983

View File

@ -7,41 +7,39 @@
[#]: via: (https://opensource.com/article/20/5/plotly-python)
[#]: author: (Shaun Taylor-Morgan https://opensource.com/users/shaun-taylor-morgan)
Simplify data visualization in Python with Plotly
使用 Plotly 来简化 Python 中的数据可视化
======
Plotly is a data plotting library with a clean interface designed to
allow you to build your own APIs.
Plotly 是一个数据绘图库,具有整洁的接口,它旨在允许你构建自己的 API。
![Colorful sound wave graph][1]
Plotly is a plotting ecosystem that allows you to make plots in [Python][2], as well as JavaScript and R. In this series of articles, I'm focusing on [plotting with Python libraries][3].
Plotly 是一个绘图生态系统,可以让你在 [Python][2] 以及 JavaScript 和 R 中进行绘图。在本文中,我将重点介绍[使用 Python 库进行绘图][3]。
Plotly has three different Python APIs, giving you a choice of how to drive it:
Plotly 有三种不同的 Python API你可以选择不同的方法来使用它
* An [object-oriented API][4] that feels similar to Matplotlib
* A [data-driven API][5] that specifies plots by constructing dictionaries of JSON-like data
* A ["Plotly Express" API][6] that gives you high-level plotting functions similar to Seaborn
* 类似于 Matplotlib 的[面向对象的 API][4]
* [数据驱动的 API][5],通过构造类似 JSON 的数据结构来指定绘图
* 类似于 Seaborn 的高级绘图接口,称为 ["Plotly Express" API][6]
我将探索使用每个 API 来绘制相同的图:英国大选结果的分组柱状图。
I'll explore each of these APIs by making the same plot in each one: a grouped bar plot of historical UK election results.
### 使用图对象来绘制图
### Making plots using Graph Objects
Plotly's object-oriented API is named graph_objects. It's somewhat similar to [Matplotlib's object-oriented API][7].
To create a multi-bar plot, you can construct a figure object containing four bar plots:
Plotly 面向对象的 API 被称为图对象,它有点类似于 [Matplotlib 的面向对象 API][7]。
要创建一个柱状图,你可以构造一个包含四个柱状图的对象:
```
    # Import Plotly and our data
    # 导入 Plotly 和数据
    import plotly.graph_objects as go
    from votes import wide as df
    # Get a convenient list of x-values
    # 得到 x 列表
    years = df['year']
    x = list(range(len(years)))
    # Specify the plots
    # 指定绘图
    bar_plots = [
      go.Bar(x=x, y=df['conservative'], name='Conservative', marker=go.bar.Marker(color='#0343df')),
      go.Bar(x=x, y=df['labour'], name='Labour', marker=go.bar.Marker(color='#e50000')),
@ -49,7 +47,7 @@ To create a multi-bar plot, you can construct a figure object containing four ba
      go.Bar(x=x, y=df['others'], name='Others', marker=go.bar.Marker(color='#929591')),
    ]
   
    # Specify the layout
    # 指定样式
    layout = go.Layout(
      title=go.layout.Title(text="Election results", x=0.5),
      yaxis_title="Seats",
@ -58,28 +56,26 @@ To create a multi-bar plot, you can construct a figure object containing four ba
      xaxis_ticktext=tuple(df['year'].values),
    )
       
    # Make the multi-bar plot
    # 绘制柱状图
    fig = go.Figure(data=bar_plots, layout=layout)
    # Tell Plotly to render it
    # 告诉 Plotly 去渲染
    fig.show()
```
Unlike in Matplotlib, there's no need to calculate the x-positions of the bars manually; Plotly takes care of that for you.
与 Matplotlib 不同的是,你无需手动计算柱状图的 x 轴位置Plotly 会帮你适配。
Here's the final plot:
最终结果图:
![A multi-bar plot made using Graph Objects][8]
A multi-bar plot made using Graph Objects (© 2019 [Anvil][9])
### Making plots using Python data structures
You can also specify your plot using basic Python data structures with the same structure as the object-oriented API. This corresponds directly to the JSON API for Plotly's JavaScript implementation.
### 使用 Python 数据结构来绘图
你还可以使用 Python 基本数据结构来指定绘图,它与面对对象 API 具有相同的结构。这直接对应于 Plotly 的 JavaScript 实现的 JSON API。
```
    # Specify the plots
    # 指定绘图数据
    fig = {
        'data': [
            {'type': 'bar', 'x': x, 'y': df['conservative'], 'name': 'Conservative', 'marker': {'color': '#0343df'}},
@ -98,29 +94,28 @@ You can also specify your plot using basic Python data structures with the same
        }
    }
    # Tell Plotly to render it
    # 告诉 Plotly 去渲染它
    pio.show(fig)
```
The final plot looks exactly the same as the previous plot:
最终结果与上次完全相同:
![A multi-bar plot made using JSON-like data structures][10]
A multi-bar plot made using JSON-like data structures (© 2019 [Anvil][9])
### Making plots using Plotly Express
#### 使用 Plotly Express 进行绘图
[Plotly Express][11] is a high-level API that wraps Graph Objects.
You can make a multi-bar plot in Plotly Express using (almost) a single line:
[Plotly Express][11] 是对图对象进行封装的高级 API。
你可以使用一行代码来绘制柱状图:
```
    # Import Plotly and our data
    # 导入 Plotly 和数据
    import plotly.express as px
    from votes import long as df
    # Define the colourmap to get custom bar colours
    # 定义颜色字典获得自定义栏颜色
    cmap = {
        'Conservative': '#0343df',
        'Labour': '#e50000',
@ -128,15 +123,14 @@ You can make a multi-bar plot in Plotly Express using (almost) a single line:
        'Others': '#929591',
    }
   
    # Make the plot!
    # 生成图
    fig = px.bar(df, x="year", y="seats", color="party", barmode="group", color_discrete_map=cmap)
```
This makes use of the data in [Long Form][12], also known as "tidy data." The columns are year, party, and seats, rather than being split by party. It's very similar to making a multi-bar plot in [Seaborn][13].
这里使用了 [Long Form][12] 数据,也称为“整洁数据”。这些列代表年份、政党和席位,而不是按政党划分。这与在 [Seaborn][13] 中制作柱状图非常相似。
```
>> print(long)
>> print(long)
     year         party  seats
0    1922  Conservative    344
1    1923  Conservative    258
@ -153,11 +147,10 @@ This makes use of the data in [Long Form][12], also known as "tidy data." The co
[108 rows x 3 columns]
```
You can access the underlying Graph Objects API to make detailed tweaks. Add a title and a y-axis label:
你可以访问底层的图对象 API 进行详细调整。如添加标题和 y 轴标签:
```
    # Use the Graph Objects API to tweak our plot
    # 使用图对象 API 来调整绘图
    import plotly.graph_objects as go
    fig.layout = go.Layout(
        title=go.layout.Title(text="Election results", x=0.5),
@ -165,42 +158,39 @@ You can access the underlying Graph Objects API to make detailed tweaks. Add a t
    )
```
And finally, ask Plotly to show it to you:
最后,让 Plotly 渲染:
```
    # Tell Plotly to render it
    fig.show()
```
This runs a temporary web server on an unused port and opens the default web browser to view the plot (the webserver is immediately torn down).
这将在未使用的端口上运行一个临时 Web 服务器,并打开默认的 Web 浏览器来查看图像Web 服务器将会马上被关闭)。
Unfortunately, the result is not perfect. The x-axis is treated as an integer, so the groups are far apart and small. This makes it quite difficult to see trends.
不幸的是结果并不完美。x 轴被视为整数,因此两组之间的距离很远且很小,这使得我们很难看到趋势。
![A multi-bar plot made using Plotly Express][14]
![使用 Plotly Express 制作的柱状图][14]
A multi-bar plot made using Plotly Express (© 2019 [Anvil][9])
You might try to encourage Plotly Express to treat the x-values as strings by casting them to strings. You might expect this to result in them being plotted with even spacing and lexical ordering. Unfortunately, you still get them helpfully spaced numerically. Setting the xaxis_tickvals does not work as it did in graph_objects, either.
你可能会尝试通过将 x 值转换为字符串来使 Plotly Express 将其视为字符串,这样它就会以均匀的间隔和词法顺序来绘制。不幸的是,它们的间隔还是很大,设置 x 值不像在图对象中那样设置。
Unlike the similar example in [Seaborn][13], in this case, the abstraction does not appear to provide sufficient [escape hatches][15] to provide things exactly how you want them. But perhaps you could write your _own_ API?
与 [Seaborn][13] 中的类似示例不同,在这种情况下,抽象似乎没有提供足够的[应急方案][15]来提供你想要的东西,但是也许你可以编写 _自己_ 的 API
### Building your own Plotly API
### 构建自己的 Plotly API
Not happy with how Plotly does something? Build your own Plotly API!
对 Plotly 的操作方式不满意?构建自己的 Plotly API
At its core, Plotly is a JavaScript library that makes plots using [D3][16] and [stack.gl][17]. The JavaScript library has an interface that consumes JSON structures that specify plots. So you just need to output JSON structures that the JavaScript library likes to consume.
Plotly 的核心是一个 JavaScript 库,它使用 [D3][16] 和 [stack.gl][17] 进行绘图。JavaScript 库的接口使用指定的 JSON 结构来绘图。因此,你只需要输出 JavaScript 库喜欢使用的 JSON 结构就好了。
Anvil did that to create a Python Plotly API that works entirely in the browser.
Anvil 这样做是为了创建一个完全在浏览器中工作的 Python Plotly API。
![Plotly uses a JavaScript library to create plots, driven by libraries in other languages via JSON][18]
![Ployly 使用 JavaScript 库创建图形,由其它语言库通过 JSON 使用][18]
Plotly uses a JavaScript library to create plots, driven by libraries in other languages via JSON  2019 [Anvil][9])
In the Anvil version, you can use both the Graph Objects API and the Python data structure approach explained above. You run exactly the same commands, assigning the data and layout to a [Plot component][19] in your Anvil app.
Here's the multi-bar plot written in Anvil's client-side Python API:
在 Anvil 版本中,你可以同时使用图对象 API 和上面介绍的 Python 数据结构方法。运行完全相同的命令,将数据和布局分配给 Anvil 应用程序中的 [Plot 组件][19]。
这是用 Anvil 的客户端 Python API 绘制的柱状图:
```
# Import Anvil libraries
@ -247,21 +237,22 @@ class Entrypoint(EntrypointTemplate):
    self.plot_1.layout = layout
```
The plotting logic is the same as above, but it's running _entirely in the web browser_—the plot is created by the Plotly JavaScript library on the user's machine! This is a big advantage over all the other [Python plotting libraries][3] in this series. All the other Python libraries need to run on a server.
绘图逻辑与上面相同,但是它完全在 Web 浏览器中运行,绘图是由用户计算机上的 Plotly JavaScript 库完成的!与本系列的所有其它 [Python 绘图库][3]相比,这是一个很大的优势。因为其它 Python 库都需要在服务器上运行。
Here's the interactive Plotly plot running in an Anvil app:
这是在 Anvil 应用中运行的交互式 Plotly 图:
![The election plot on the web using Anvil's client-side-Python Plotly library][20]
The election plot on the web using Anvil's [client-side-Python][21] Plotly library (© 2019 [Anvil][9])
使用 Anvil 的 [Python 客户端][21] Plotly 库在网络上进行选举的情节 (© 2019 [Anvil][9])
You can [copy this example][22] as an Anvil app (Note: Anvil requires registration to use).
你可以[复制此示例][22]作为一个 Anvil 应用程序注意Anvil 需要注册才能使用)。
Running Plotly in the frontend has another advantage: it opens up many more options for customizing interactive behavior.
在前端运行 Plotly 还有另一个优势:它为自定义交互行为提供了更多选项。
### Customizing interactivity in Plotly
### 在 Plotly 中自定义交互
Plotly plots aren't just dynamic; you can customize their interactive behavior. For example, you can customize the format of tool-tips using hovertemplate in each bar plot:
Plotly 绘图不仅是动态的,你可以自定义它们的互动行为。例如,你可以在每个条形图中使用 hovertemplate 自定义工具提示的格式:
```
@ -274,20 +265,20 @@ Plotly plots aren't just dynamic; you can customize their interactive behavior.
    ),
```
Here's what you get when you apply this to each bar plot:
当你把这个应用到每个柱状图时,你会看到以下结果:
![A multi-bar plot with custom tool-tips][23]
A multi-bar plot with custom tool-tips (© 2019 [Anvil][9])
This is useful, but it would be even better if you could execute any code you want when certain events happen—like when a user hovers over the bar and you want to display an information box about the relevant election. In Anvil's Plotly library, you can bind event handlers to events such as hover, which makes that sort of complex interactivity possible!
这很有用,当你想要在某些事件发生时执行另一些事件时它会表现的更好(例如,当用户将鼠标悬停在栏上,你想要显示有关相关选择的信息框)。在 Anvil 的 Plotly 库中,你可以将事件处理程序绑定到诸如悬停之类的事件,这使得复杂的交互成为可能。
![A multi-bar plot with a hover event handler][24]
A multi-bar plot with a hover event handler (© 2019 [Anvil][9])
You can achieve this by binding a method to the plot's hover event:
你可以通过将方法绑定到绘图的悬停事件来实现:
```
  def plot_1_hover(self, points, **event_args):
@ -303,19 +294,18 @@ You can achieve this by binding a method to the plot's hover event:
    self.link_more_info.url = url
```
This is a rather extreme level of interactivity, and from the developer's point of view, an extreme level of customizability. It's all thanks to Plotly's architecture—Plotly has a clean interface that is explicitly designed to allow you to build your own APIs. It would be helpful to see this kind of great design everywhere!
这是一种相当极端的交互性,从开发人员的角度来看,也是一种极端的可定制性。这都要归功于 Plotly 的架构 - 它有一个整洁的接口,明确设计用于构建自己的 API。到处都可以看到这种出色的设计
### Custom interactivity using Bokeh
### 使用 Bokeh 进行自定义交互
You've seen how Plotly uses JavaScript to create dynamic plots, and you can edit them live in the browser using Anvil's client-side Python code.
现在你已经了解了 Plotly 如何使用 JavaScript 来创建动态图,并且可以使用 Anvil 的客户端编写 Python 代码在浏览器中实时编辑它们。
Bokeh is another Python plotting library that outputs an HTML document you can embed in a web app and get similar dynamic features to those provided by Plotly. (That's "BOE-kay," if you're wondering how to pronounce it.)
Bokeh 是另一个 Python 绘图库,它输出可嵌入 Web 应用程序的 HTML 文档,并获得与 Plotly 提供的功能类似的动态功能(如果你想知道如何发音,那就是 "BOE-kay")。
Enjoy customizing charts and share tips and tricks in the comments below.
* * *
_This article is based on [How to make plots using Plotly][9] on Anvil's blog and is reused with permission._
_本文基于 Anvil 博客中的 [如何使用 Plotly 来绘图][9]一文,已允许使用。_
--------------------------------------------------------------------------------
@ -323,7 +313,7 @@ via: https://opensource.com/article/20/5/plotly-python
作者:[Shaun Taylor-Morgan][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
译者:[MjSeven](https://github.com/MjSeven)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出