如何在Plotly Express散点图中手动设置点的颜色。

30

https://plotly.com/python/line-and-scatter/有许多散点图例子,但没有一个示范如何在px.scatter中设置所有点的颜色:

# x and y given as DataFrame columns
import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame
fig = px.scatter(df, x="sepal_width", y="sepal_length")
fig.show()

我尝试了添加 colour = 'red' 之类的方法,但并没有起作用。这些示例仅显示如何通过其他变量着色。

原则上,我可以添加另一个特征并将其全部设置为相同,但这似乎是一种奇怪的完成任务的方式......

3个回答

22

为此,您可以使用color_discrete_sequence参数。

fig = px.scatter(df, x="sepal_width", y="sepal_length", color_discrete_sequence=['red'])

这个参数是用来为离散的 color 因子使用自定义颜色调色板的,但是如果您没有使用任何 color 因子,它将对绘图中的所有点使用第一个元素。

有关离散颜色调色板的更多信息:https://plotly.com/python/discrete-color/


对于只接受 surfacecolorgo.Surface,怎么样? - aviator

6
在我理解你的问题的范围内,我会尝试回答它。
参数 'color' 只接受列名。
在您的情况下,可以考虑使用 update_traces()。
import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame
fig = px.scatter(df, x="sepal_width", y="sepal_length")
fig.update_traces(marker=dict(
        color='red'))
fig.show()

参考文献:https://plotly.com/python/marker-style/


1
谢谢,但相比于其他绘图包(ggplot,matplotlib等),那个系统确实疯狂。 - RNs_Ghost

5
你不需要添加其他功能来实现你想要的效果。由于Python的方法链接,你只需包含.update_traces(marker=dict(color='red'))就可以手动为所有标记指定任何颜色。谢谢。 图表:

enter image description here

代码:

# x and y given as DataFrame columns
import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame
fig = px.scatter(df,x="sepal_width",                         
                    y="sepal_length"
                 ).update_traces(marker=dict(color='red'))
fig.show()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接