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

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

Plotly是一个开源的Python库,用于创建交互式的基于Web的图表。在本教程中,我们将展示如何使用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()

输出

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

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

同样,您可以尝试创建不同类型的图像。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程