Python Plotly – 如何在散点图中同时应用颜色/形状/大小?


Plotly 是一个用于创建交互式基于 Web 的图表开源 Python 库。在本教程中,我们将展示如何使用 Plotly 在散点图中应用颜色/形状/大小。

  • 在这里,我们将使用 **plotly.graph_objects** 模块生成图形。它包含许多生成图表的方法。

  • 此外,我们将使用 **add_trace()** 方法创建散点图,然后使用 add_shape() 方法设置类型、形状和线条颜色。

  • 最后,我们将使用 **update_layout()** 方法设置图表的宽度和高度。

请按照以下步骤在散点图中应用颜色/形状。

步骤 1

导入 **plotly.graphs_objs** 模块并将其别名为 **go**。

import plotly.graphs_objs as go

步骤 2

使用 **add_trace()** 方法生成散点图。

# Create scatter trace of text labels
fig.add_trace(go.Scatter(
   x=[1.5, 3.5],
   y=[0.75, 2.5],
   text=["Circle", "Filled Circle"],
   mode="text",
))

步骤 3

使用 **update_axes()** 方法更新散点图的轨迹。

# Set axes properties
fig.update_xaxes(range=[0, 4.5], zeroline=False)
fig.update_yaxes(range=[0, 4.5])

步骤 4

使用 **add_shape()** 方法在图表上添加两个圆形。

# Add circles
fig.add_shape(type="circle", xref="x", yref="y", x0=1, y0=1, x1=3, y1=3, line_color="LightGreen", )
fig.add_shape(type="circle", xref="x", yref="y", fillcolor="pink", x0=3, y0=3, x1=4, y1=4, line_color="LightGreen",)

步骤 5

使用 **update_layout()** 方法设置图表的宽度和高度 -

# Set figure size
fig.update_layout(width=800, height=800)

示例

应用颜色/形状/大小的完整代码如下所示 -

import plotly.graph_objects as go fig = go.Figure() # Create scatter trace of text labels fig.add_trace(go.Scatter( x=[1.5, 3.5], y=[0.75, 2.5], text=["Circle", "Filled Circle"], mode="text", )) # Set axes properties fig.update_xaxes(range=[0, 4.5], zeroline=False) fig.update_yaxes(range=[0, 4.5]) # Add circles fig.add_shape(type="circle", xref="x", yref="y", x0=1, y0=1, x1=3, y1=3, line_color="LightGreen",) fig.add_shape(type="circle", xref="x", yref="y", fillcolor="pink", x0=3, y0=3, x1=4, y1=4, line_color="LightGreen", ) # Set figure size fig.update_layout(width=716, height=400) fig.show()

输出

执行后,它将在浏览器上显示以下输出 -

类似地,您可以尝试创建不同类型的图形作为图像。

更新于: 2022-10-21

1K+ 次查看

启动您的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.