【问题标题】:Plotly: How to manually set the color of points in plotly express scatter plots?Plotly:如何手动设置 plotly express 散点图中点的颜色?
【发布时间】:2020-12-04 09:50:41
【问题描述】:

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' 等不起作用。这些示例仅向您展示如何通过其他变量进行着色。

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

【问题讨论】:

    标签: python plotly plotly-python


    【解决方案1】:

    为此,您可以使用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/

    【讨论】:

      【解决方案2】:

      据我了解你的问题,我会尽力回答。

      参数 '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/

      【讨论】:

      • 谢谢,但与其他绘图包(ggplot、matplotlib 等)相比,这确实是一个非常疯狂的系统
      【解决方案3】:

      无需添加其他功能即可在此处获得所需的内容。感谢 Python 的method chaining,您只需包含.update_traces(marker=dict(color='red')) 即可手动将您选择的任何颜色分配给所有标记。

      剧情:

      代码:

      # 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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-27
        • 2021-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多