英文:
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()
英文:
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({
'random_walk': rw,
'color': 10*['black'] + 50 * ['blue'] + 40*['black'],
'x': range(100)
})
## Break your dataframe into an array of smaller dataframes, each with single color
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)
## Plot the first line - dfs[0]
fig = px.line(dfs[0], x='x', y='random_walk')
fig.update_traces(line_color=dfs[0]['color'].iloc[0])
## For other lines in array, plot new line
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论