如何在Plotly中绘制一条单线,并根据分类变量使用多种颜色。

huangapple go评论83阅读模式
英文:

how to plot a single line in plotly with multiple colors according to a categorical variable

问题

如何在plotly中获得一条单一连接线,并使用不同的颜色?

下面的图表显示了解决方案的尝试。然而,线在点10和点90之间有一个不美观的中断。如何根据分类变量拥有单一线并使用多种颜色,而不会中断?

import numpy as np
import random
import pandas as pd
import plotly.express as px

white_noise = np.array([random.gauss(mu=0.0, sigma=1.0) for x in range(100)])
rw = white_noise.cumsum()
rw_df = pd.DataFrame({
    'random_walk': rw, 
    'color': 10*['black'] + 50 * ['blue'] + 40*['black'], 
    'x': range(100)
})

fig = px.line(rw_df, x='x', y='random_walk', color='color')
fig.show()


[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/eelrG.png

<details>
<summary>英文:</summary>

How can I get a single connected line in `plotly` with different colors?

The plot below shows an attempt at a solution.  However, the line has an ugly break between point 10 and point 90.  How can I have a single line with multiple colors according to a categorical variable without breaking?[![enter image description here][1]][1]

import numpy as np
import random
import pandas as pd
import plotly.express as px

white_noise = np.array([random.gauss(mu=0.0, sigma=1.0) for x in range(100)])
rw = white_noise.cumsum()
rw_df = pd.DataFrame({
'random_walk': rw,
'color': 10*['black'] + 50 * ['blue'] + 40*['black'],
'x': range(100)
})```

fig = px.line(rw_df, x='x', y='random_walk', color='color')
fig.show()



  [1]: https://i.stack.imgur.com/eelrG.png

</details>


# 答案1
**得分**: 1

以下是您要翻译的代码部分:

```python
import numpy as np
import random
import pandas as pd
import plotly.express as px

white_noise = np.array([random.gauss(mu=0.0, sigma=1.0) for x in range(100)])
rw = white_noise.cumsum()
rw_df = pd.DataFrame({
    'random_walk': rw, 
    'color': 10*['black'] + 50 * ['blue'] + 40*['black'], 
    'x': range(100)
})

## 将数据框拆分为一组颜色相同的数据框
rw_df['group']=rw_df['color'].ne(rw_df['color'].shift()).cumsum()
rw_df
rw_df = rw_df.groupby('group')
dfs = []
for name, data in rw_df:
    dfs.append(data)

## 绘制第一条线 - dfs[0]    
fig = px.line(dfs[0], x='x', y='random_walk')
fig.update_traces(line_color=dfs[0]['color'].iloc[0])

## 对于数组中的其他线条,绘制新的线条
for i in range(1, len(dfs)):
    fig.add_scatter(x=dfs[i]["x"], y=dfs[i]["random_walk"], 
                    line_color=dfs[i]['color'].iloc[0], 
                    name=dfs[i]['color'].iloc[0])
    
fig.show()

如何在Plotly中绘制一条单线,并根据分类变量使用多种颜色。

英文:

See if this is what you are looking for...

First - break the dataframe into an array of dataframes, each with a set of same colored rows... in your example, it would be 3 dataframes - first for the black line, second for blue and then another for the black.

Second - Plot the first item as a line. Then for each subsequent dataframes, use add scatter to plot a new line.

import numpy as np
import random
import pandas as pd
import plotly.express as px

white_noise = np.array([random.gauss(mu=0.0, sigma=1.0) for x in range(100)])
rw = white_noise.cumsum()
rw_df = pd.DataFrame({
    &#39;random_walk&#39;: rw, 
    &#39;color&#39;: 10*[&#39;black&#39;] + 50 * [&#39;blue&#39;] + 40*[&#39;black&#39;], 
    &#39;x&#39;: range(100)
})

## Break your dataframe into an array of smaller dataframes, each with single color
rw_df[&#39;group&#39;]=rw_df[&#39;color&#39;].ne(rw_df[&#39;color&#39;].shift()).cumsum()
rw_df
rw_df = rw_df.groupby(&#39;group&#39;)
dfs = []
for name, data in rw_df:
    dfs.append(data)

## Plot the first line - dfs[0]    
fig = px.line(dfs[0], x=&#39;x&#39;, y=&#39;random_walk&#39;)
fig.update_traces(line_color=dfs[0][&#39;color&#39;].iloc[0])

## For other lines in array, plot new line
for i in range(1, len(dfs)):
    fig.add_scatter(x=dfs[i][&quot;x&quot;], y=dfs[i][&quot;random_walk&quot;], 
                    line_color=dfs[i][&#39;color&#39;].iloc[0], 
                    name=dfs[i][&#39;color&#39;].iloc[0])
    
fig.show()

如何在Plotly中绘制一条单线,并根据分类变量使用多种颜色。

huangapple
  • 本文由 发表于 2023年6月1日 13:26:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定