自定义颜色

Python 中的 Plotly 数据可视化入门

Alex Scriven

Data Scientist

通用自定义方法

 

自定义图表的方式:

  1. 在创建时,使用相应参数(如 color
  2. 创建后,用 update_layout()
    • 接收字典
    • fig.update_layout({"title":{"text":"A New Title"}})
Python 中的 Plotly 数据可视化入门

为何自定义颜色?

 

自定义颜色有助于:

  1. 让图表更出彩
  2. 传达分析洞见
    • 此散点图用颜色作为第 3 维。

   

以物种为颜色

Python 中的 Plotly 数据可视化入门

一些颜色基础

 

计算机用 RGB 编码表示颜色:

  • RGB = 三位数值(各 0–255),混合红、绿、蓝
    • (0,0,255) 为蓝色,(255,255,0) 为黄色

$$

$$

更多请见此文章

RGB 颜色示例表

Python 中的 Plotly 数据可视化入门

在 plotly.express 中指定颜色

 

  • color 参数(DataFrame 列)
    • 每个类别会被分配一种颜色(自动)
    • 数值列使用颜色刻度

 

fig = px.bar(data_frame=student_scores, 
      x="student_name", 
      y="score", 
      title="Student Scores by Student"
      color="city")
fig.show()
Python 中的 Plotly 数据可视化入门

揭示我们的颜色

之前的图:

无颜色的柱状图

之后的图:

带颜色的柱状图

Python 中的 Plotly 数据可视化入门

单变量图中的颜色

 

在单变量(柱状图、直方图)中使用 plotly.expresscolor 参数:

  • 直方图——堆叠柱
  • 箱线图——生成多个图

带颜色的堆叠直方图

并排的带颜色箱线图

Python 中的 Plotly 数据可视化入门

plotly.express 中的指定颜色

 

  • color_discrete_map:将分类值映射到颜色的字典
  • 也可用字符串表示基础颜色,如 "red""green"
Python 中的 Plotly 数据可视化入门

我们的指定颜色

$$

fig = px.bar(
    data_frame=student_scores, 
    x="student_name", y="score", 
    title="Student Scores by Student",

color_discrete_map={ "Melbourne": "rgb(0,0,128)", "Sydney": "rgb(235, 207, 52)"},
color="city")

 

指定颜色的柱状图

Python 中的 Plotly 数据可视化入门

plotly.express 中的颜色刻度

 

  • 单色刻度(浅到深绿)

绿色颜色刻度

  • 渐变(绿到蓝)

$$

  • 使用 color_continuous_scale 指定颜色刻度。

绿蓝颜色刻度

Python 中的 Plotly 数据可视化入门

使用内置颜色刻度

 

fig = px.bar(data_frame=weekly_temps, 
    x="day", y="temp", 
    color="temp",
    color_continuous_scale="inferno")
fig.show()

 

$$

 

Inferno 颜色刻度的柱状图

Python 中的 Plotly 数据可视化入门

构建自定义颜色范围

 

  • 自定义刻度(黄 - 橙 - 红)
my_scale=[("rgb(242, 238, 10)"),
          ("rgb(242, 95, 10)"), 
          ("rgb(255,0,0)")]

fig = px.bar(data_frame=weekly_temps, x="day", y="temp",
color_continuous_scale=my_scale, color="temp")

 

自定义颜色刻度的柱状图

Python 中的 Plotly 数据可视化入门

让我们练习吧!

Python 中的 Plotly 数据可视化入门

Preparing Video For Download...