简体   繁体   English

Plotly:如何使用883276440288 Graph Objects和Plotly Express在图中定义colors?

[英]Plotly: How to define colors in a figure using Plotly Graph Objects and Plotly Express?

There are many questions and answers that touch upon this topic one way or another.有许多问题和答案以某种方式涉及到这个主题。 With this contribution I'd like to clearly show why an easy approch such as marker = {'color': 'red'} will work for plotly.graph_objects (go) , but color='red' will not for plotly.express (px) although color is an attribute of both px.Line and px.Scatter .有了这个贡献,我想清楚地说明为什么像marker = {'color': 'red'}这样的简单方法适用于plotly.graph_objects (go) ,但color='red'不适用于plotly.express (px)尽管颜色是px.Linepx.Scatter的属性。 And I'd like to demonstrate why it's awesome that it doesn't.想证明为什么它不是很棒。


So, if px is supposed to be the easiest way to make a plotly figure , then why does something as apparently obvious as color='red' return the error所以,如果px应该是制作 plotly 图形的最简单方法,那么为什么像color='red'这样明显的东西会返回错误

ValueError: Value of 'color' is not the name of a column in 'data_frame'. ValueError:“color”的值不是“data_frame”中列的名称。

To put it short, it's because color in px does not accept an arbitrary color name or code, but rather a variable name in your dataset in order to assign a color cycle to unique values and display them as lines with different colors.简而言之,这是因为color in px不接受任意颜色名称或代码,而是接受数据集中的变量名称,以便将颜色循环分配给唯一值并将它们显示为具有不同 colors 的行。

Let me demonstrate by applyig a gapminder dataset and show a scatterplot of Life expectancy versus GDP per capita for all (at least most ) countries across the world as of 2007 .让我通过应用gapminder数据集来演示,并显示截至2007世界上所有(至少大多数)国家的Life expectancyGDP per capita的散点图。 A basic setup like below will produce the following plot像下面这样的基本设置将产生以下 plot

Figure 1, plot using go :图 1,plot 使用go

在此处输入图像描述

The color is set by a cycle named plotly but is here specified using marker = {'color': 'red'}颜色由名为plotly的循环设置,但此处使用marker = {'color': 'red'}指定

Figure 2, code:图2,代码:

import plotly.graph_objects as go

df = px.data.gapminder()
df=df.query("year==2007")

fig = go.Figure()
fig.add_traces(go.Scatter(x=df['gdpPercap'], y=df["lifeExp"],
                          mode = 'markers',
                          marker = {'color' : 'red'}
                         ))
fig.show()

So let's try this with px , and assume that color='red' would do the trick:所以让我们用px试试这个,并假设color='red'可以解决这个问题:

Code 2, attempt at scatter plot with defined color using px :代码 2,尝试使用px以定义的颜色散布 plot:

# imports
import plotly.express as px
import pandas as pd

# dataframe
df = px.data.gapminder()
df=df.query("year==2007")

# plotly express scatter plot
px.scatter(df, x="gdpPercap", y="lifeExp",
           color = 'red',
          )

Result:结果:

ValueError: Value of 'color' is not the name of a column in 'data_frame'. ValueError:“color”的值不是“data_frame”中列的名称。 Expected one of ['country', 'continent', 'year', 'lifeExp', 'pop', 'gdpPercap', 'iso_alpha', 'iso_num'] but received: red预期 ['country', 'continent', 'year', 'lifeExp', 'pop', 'gdpPercap', 'iso_alpha', 'iso_num'] 之一但收到:红色

So what's going on here?那么这是怎么回事?

First, if an explanation of the broader differences between go and px is required, please take a look here and here .首先,如果需要解释gopx之间更广泛的差异,请查看此处此处 And if absolutely no explanations are needed, you'll find a complete code snippet at the very end of the answer which will reveal many of the powers with colors in plotly.express如果绝对不需要任何解释,您会在答案的最后找到一个完整的代码片段,它将揭示 plotly.express 中 colors 的许多功能


Part 1: The Essence:第 1 部分:本质:

It might not seem so at first, but there are very good reasons why color='red' does not work as you might expect using px .乍一看似乎并非如此,但充分的理由说明为什么color='red'不能像您预期的那样使用px But first of all, if all you'd like to do is manually set a particular color for all markers you can do so using .update_traces(marker=dict(color='red')) thanks to pythons chaining method .但首先,如果你想做的只是手动为所有标记设置特定颜色,你可以使用.update_traces(marker=dict(color='red'))多亏了pythons 链接方法 But first, lets look at the deafult settings:但首先,让我们看一下默认设置:

1.1 Plotly express defaults 1.1 Plotly 快递默认

Figure 1, px default scatterplot using px.Scatter图一、px默认散点图使用px.Scatter

在此处输入图像描述

Code 1, px default scatterplot using px.Scatter代码1、px默认散点图使用px.Scatter

# imports
import plotly.express as px
import pandas as pd

# dataframe
df = px.data.gapminder()
df=df.query("year==2007")

# plotly express scatter plot
px.scatter(df, x="gdpPercap", y="lifeExp")

Here, as already mentioned in the question, the color is set as the first color in the default plotly sequence available through px.colors.qualitative.Plotly :在这里,正如问题中已经提到的,颜色被设置为默认 plotly 序列中的第一种颜色,可通过px.colors.qualitative.Plotly

['#636EFA', # the plotly blue you can see above
 '#EF553B',
 '#00CC96',
 '#AB63FA',
 '#FFA15A',
 '#19D3F3',
 '#FF6692',
 '#B6E880',
 '#FF97FF',
 '#FECB52']

And that looks pretty good.这看起来很不错。 But what if you want to change things and even add more information at the same time?但是,如果您想更改内容甚至同时添加更多信息怎么办?

1.2: How to override the defaults and do exactly what you want with px colors: 1.2:如何覆盖默认值并使用 px colors完全按照您的意愿进行操作:

As we alread touched upon with px.scatter , the color attribute does not take a color like red as an argument.正如我们已经接触过的px.scattercolor属性不接受像red这样的颜色作为参数。 Rather, you can for example use color='continent' to easily distinguish between different variables in a dataset.相反,您可以使用color='continent'轻松区分数据集中的不同变量。 But there's so much more to colors in px :但是px中的 colors 还有很多:


The combination of the six following methods will let you do exactly what you'd like with colors using plotly express.结合使用以下六种方法,您可以使用 plotly express完全按照自己的意愿使用 colors。 Bear in mind that you do not even have to choose .请记住,您甚至不必选择 You can use one , some , or all of the methods below at the same time.您可以同时使用以下一种部分所有方法。 And one particular useful approach will reveal itself as a combinatino of 1 and 3 .一种特别有用的方法将显示为13的组合。 But we'll get to that in a bit.但我们稍后会谈到这一点。 This is what you need to know:这是你需要知道的:

1. Change the color sequence used by px with: 1.更改 px 使用的颜色顺序:

color_discrete_sequence=px.colors.qualitative.Alphabet

2. Assign different colors to different variables with the color argument 2.将不同的 colors 赋值给不同的变量,使用color参数

color = 'continent'

3. customize one or more variable colors with 3.自定义一个或多个变量colors with

color_discrete_map={"Asia": 'red'}

4. Easily group a larger subset of your variables using dict comprehension and color_discrete_map 4.使用字典理解和color_discrete_map轻松对更大的变量子集进行分组

subset = {"Asia", "Africa", "Oceania"}
group_color = {i: 'red' for i in subset}

5. Set opacity using rgba() color codes. 5.使用rgba()颜色代码设置不透明度。

color_discrete_map={"Asia": 'rgba(255,0,0,0.4)'}

6. Override all settings with: 6.覆盖所有设置:

.update_traces(marker=dict(color='red'))

Part 2: The details and the plots第 2 部分:细节和情节

The following snippet will produce the plot below that shows life expectany for all continents for varying levels of GDP.以下代码段将生成下面的 plot,它显示了所有大陆在不同 GDP 水平下的预期寿命。 The size of the markers representes different levels of populations to make things more interesting right from the get go.标记的大小代表不同级别的人口,从 go 开始让事情变得更有趣。

Plot 2: Plot 2:

在此处输入图像描述

Code 2:代码 2:

import plotly.express as px
import pandas as pd

# dataframe, input
df = px.data.gapminder()
df=df.query("year==2007")

px.scatter(df, x="gdpPercap", y="lifeExp",
           color = 'continent',
           size='pop',
          )

To illustrate the flexibility of the methods above, lets first just change the color sequence .为了说明上述方法的灵活性,让我们首先改变颜色顺序 Since we for starters are only showing one category and one color, you'll have to wait for the subsequent steps to see the real effects.由于我们一开始只展示了一种类别和一种颜色,您必须等待后续步骤才能看到真正的效果。 But here's the same plot now with color_discrete_sequence=px.colors.qualitative.Alphabet as per step 1:但是这里是相同的 plot 现在color_discrete_sequence=px.colors.qualitative.Alphabet按照步骤 1:

1. Change the color sequence used by px with 1.改变px使用的颜色序列

color_discrete_sequence=px.colors.qualitative.Alphabet

在此处输入图像描述

Now, let's apply the colors from the Alphabet color sequence to the different continents:现在,让我们将Alphabet颜色序列中的 colors 应用到不同的大陆:

2. Assign different colors to different variables with the color argument 2.将不同的 colors 赋值给不同的变量,使用color参数

color = 'continent'

在此处输入图像描述

If you, like me, think that this particular color sequence is easy on the eye but perhaps a bit indistinguishable, you can assign a color of your choosing to one or more continents like this:如果你和我一样,认为这个特定的颜色序列在眼睛上很容易,但可能有点难以区分,你可以将你选择的颜色分配给一个或多个大陆,如下所示:

3. customize one or more variable colors with 3.自定义一个或多个变量colors with

color_discrete_map={"Asia": 'red'}

在此处输入图像描述

And this is pretty awesome: Now you can change the sequence and choose any color you'd like for particularly interesting variables.这非常棒:现在您可以更改顺序并为特别有趣的变量选择您喜欢的任何颜色。 But the method above can get a bit tedious if you'd like to assign a particular color to a larger subset.但是如果您想将特定颜色分配给更大的子集,上述方法可能会有点乏味。 So here's how you can do that too with a dict comprehension :所以你也可以通过听写理解来做到这一点:

4. Assign colors to a group using a dict comprehension and color_discrete_map 4.使用字典理解和color_discrete_map将 colors 分配给一个组

# imports
import plotly.express as px
import pandas as pd

# dataframe
df = px.data.gapminder()
df=df.query("year==2007")

subset = {"Asia", "Europe", "Oceania"}
group_color = {i: 'red' for i in subset}

# plotly express scatter plot
px.scatter(df, x="gdpPercap", y="lifeExp",
           size='pop',
           color='continent',
           color_discrete_sequence=px.colors.qualitative.Alphabet,
           color_discrete_map=group_color
          )

在此处输入图像描述

5. Set opacity using rgba() color codes. 5.使用rgba()颜色代码设置不透明度。

Now let's take one step back.现在让我们退后一步。 If you think red suits Asia just fine, but is perhaps a bit too strong, you can adjust the opacity using a rgba color like 'rgba(255,0,0,0.4)' to get this:如果您认为red很适合亚洲,但可能有点太浓了,您可以使用rgba颜色调整不透明度,例如'rgba(255,0,0,0.4)'以获得此效果:

在此处输入图像描述

Complete code for the last plot:最后一个plot的完整代码:

import plotly.express as px
import pandas as pd

# dataframe, input
df = px.data.gapminder()
df=df.query("year==2007")

px.scatter(df, x="gdpPercap", y="lifeExp",
           color_discrete_sequence=px.colors.qualitative.Alphabet,
           color = 'continent',
           size='pop',
           color_discrete_map={"Asia": 'rgba(255,0,0,0.4)'}
          )

And if you think we're getting a bit too complicated by now, you can override all settings like this again:如果你认为我们现在变得有点太复杂了,你可以像这样再次覆盖所有设置:

6. Override all settings with: 6.覆盖所有设置:

.update_traces(marker=dict(color='red'))

在此处输入图像描述

And this brings us right back to where we started.这让我们回到了起点。 I hope you'll find this useful!我希望你会发现这很有用!

Complete code snippet with all options available:包含所有可用选项的完整代码片段:

# imports
import plotly.express as px
import pandas as pd

# dataframe
df = px.data.gapminder()
df=df.query("year==2007")

subset = {"Asia", "Europe", "Oceania"}
group_color = {i: 'red' for i in subset}

# plotly express scatter plot
px.scatter(df, x="gdpPercap", y="lifeExp",
           size='pop',
           color='continent',
           color_discrete_sequence=px.colors.qualitative.Alphabet,
           #color_discrete_map=group_color
           color_discrete_map={"Asia": 'rgba(255,0,0,0.4)'}
          )#.update_traces(marker=dict(color='red'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Plotly:如何使用 Python 对 plotly 图形对象条形图进行颜色编码? - Plotly: How to colorcode plotly graph objects bar chart using Python? Plotly:如何 plot 使用 plotly 和 Z26C592956DC26CA26AEF5DBACC204A03 回归线? - Plotly: How to plot a regression line using plotly and plotly express? plotly - 在 Plot.JS 中使用 graph_objects.Figure 跟踪 - plotly - Using graph_objects.Figure traces in Plot.JS 如何更改 plotly.graph_objects.Figure 的刻度标签? - How to change tick labels for plotly.graph_objects.Figure? Plotly:如何在 plotly 快递图上添加水平滚动条? - Plotly: How to add a horizontal scrollbar to a plotly express figure? Plotly:如何使用新数据更新/重绘绘图表达图形? - Plotly: How to update / redraw a plotly express figure with new data? Plotly:如何在 plotly 中隐藏轴标题? - Plotly: How to hide axis titles in a plotly express figure with facets? 如何删除 plotly express 图形对象中的网格线(python) - How do I remove gridlines in plotly express graph objects (python) 如何使用 graph_objects 子模块在可绘制的旭日图上设置颜色? - How can I set the colors on a plotly sunburst chart using the graph_objects submodule? Plotly 中的连续色标 -- plotly.express 为 px,plotly.graph_objects 为 go - Continuous Color Scales in Plotly -- plotly.express as px, and plotly.graph_objects as go
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM