Python Plotly – 子图和插图
附加条件: Python Plotly
Plotly 数据可视化最具欺骗性的强大功能之一是当将光标指向出现的点标签时,查看者能够快速分析足够数量的数据信息。
在本文中,我们将了解 Plotly 中的子图和插图。
Syntax: layout = go.Layout( xaxis2 = dict( domain = [0-1], anchor = ‘axis’)
Where:
- xaxis2: list
- anchor: position_axis
示例 1:绘制子图
subplots 方法提供了一种在单个图形上绘制多个图的方法。这支持在 plotly.tools 模块中提供函数的子图的概念。该函数返回一个 Figure 对象。在此示例中,我们使用两个数据图,第一个是折线图,另一个是直方图。
Python3
from plotly import tools
import plotly.graph_objs as go
from plotly.offline import iplot
import numpy as np
# defining data for chart 1
x1 = np.array([22, 87, 5, 43, 56, 73, 11,
42, 20, 5, 31, 27, 85])
# defining data for chart 2
N = 100
x_vals = np.linspace(0, 1, N)
y_vals = np.random.randn(N) - 5
# chart 1
chart1 = go.Histogram(x=x1)
# chart 2
chart2 = go.Scatter(
x=x_vals,
y=y_vals,
mode='lines',
name='line',
xaxis='x2',
yaxis='y2',
)
fig = tools.make_subplots(rows=1, cols=2)
fig.append_trace(chart1, 1, 1)
fig.append_trace(chart2, 1, 2)
fig['layout'].update(height=600, width=800,
title='subplot')
iplot(fig)
Python3
from plotly import tools
import plotly.graph_objs as go
from plotly.offline import iplot
import numpy as np
# defining data for chart 1
x1 = np.array([22, 87, 5, 43, 56, 73, 11,
42, 20, 5, 31, 27, 85])
# defining data for chart 2
N = 100
x_vals = np.linspace(0, 1, N)
y_vals = np.random.randn(N) - 5
# chart 1
chart1 = go.Histogram(x=x1)
# chart 2
chart2 = go.Scatter(
x=x_vals,
y=y_vals,
mode='lines',
name='line',
xaxis='x2',
yaxis='y2',
)
data = [chart1, chart2]
# setting layout
layout = go.Layout(
# setting y-axis position for chart 2
xaxis2=dict(
domain=[0.65, 0.95],
anchor='y2'
),
# setting y-axis position for chart 2
yaxis2=dict(
domain=[0.6, 0.95],
anchor='x2'
)
)
fig = go.Figure(data=data, layout=layout)
iplot(fig)
输出:
示例 2:Plotly 插入图
插图是值和数据的图形表示。它是一个添加到给定子图图表中的现有图表的图表。插图的尺寸减小了,因此主图在图表中至少部分可见。它为我们提供了从文档中读取和分析信息的最简单方法。
在此示例中,我们使用两个数据图,第一个是折线图,另一个是直方图,分配为 chart1,chart2 在布局方法中作为列表传递。插图的 x 轴和 y 轴属性分别跟踪到“x2”和“y2”。
现在,可以将 x 轴锚定到 y 轴,例如, xaxis2: {anchor: 'y2'}表示xaxis2在原点连接yaxis2 。如果锚点设置为自由,则可以使用位置属性将轴移动到另一个位置。
Python3
from plotly import tools
import plotly.graph_objs as go
from plotly.offline import iplot
import numpy as np
# defining data for chart 1
x1 = np.array([22, 87, 5, 43, 56, 73, 11,
42, 20, 5, 31, 27, 85])
# defining data for chart 2
N = 100
x_vals = np.linspace(0, 1, N)
y_vals = np.random.randn(N) - 5
# chart 1
chart1 = go.Histogram(x=x1)
# chart 2
chart2 = go.Scatter(
x=x_vals,
y=y_vals,
mode='lines',
name='line',
xaxis='x2',
yaxis='y2',
)
data = [chart1, chart2]
# setting layout
layout = go.Layout(
# setting y-axis position for chart 2
xaxis2=dict(
domain=[0.65, 0.95],
anchor='y2'
),
# setting y-axis position for chart 2
yaxis2=dict(
domain=[0.6, 0.95],
anchor='x2'
)
)
fig = go.Figure(data=data, layout=layout)
iplot(fig)
输出: