Why is go.Scatter printing extra lines whereas px.line is not?(为什么 go.Scatter 打印额外的行而 px.line 不是?)
问题描述
Here is my code for graph_objects-
go.Figure(go.Scatter(x=continent_df.date, y=continent_df.new_cases_smoothed))
Whereas my code for plotly express is this -
px.line(continent_df, x='date', y='new_cases_smoothed', color='continent')
Why does the first graph print extra straight lines for each continent? I already tried sorting the dataframe.
continent_df.sort_values(['continent','date'], inplace=True)
(Also, how can I color code each line in the first graph as it is done in the second one?)
I can't be 100% sure without a proper sample of your data. But it seems that your dataset is of a long format with multiple values in continent_df.new_cases_smoothed
belonging to different contients. And you're assigning all these values to one single trace using go.Figure(go.Scatter(x=continent_df.date, y=continent_df.new_cases_smoothed))
.
The straight lines are there because there's only one line that goes back and forth and covers all categories and all indexes. The straight parts of the line appear when it goes back to the beginning and starts showing a new category
However, using px.line
here takes care of that by grouping the continents using color='continent'
. Hence making the value categories appear as unique traces.
We can use the gapminder dataset, which has a structure similar to your real world data, to illustrate how to assign individual traces to a go.Figure
using fig.add_traces(go.Scatter())
. The key is to retrieve unique categories, subset your data, and add groups line by line. This gives you arguably greater flexibility compared to using px.line
.
Plot
Code
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
# Data
gap = px.data.gapminder()
fig = go.Figure()
for c in gap['country'].unique()[:10]:
df = gap[gap['country']==c]
fig.add_traces(go.Scatter(x=df['year'], y = df['lifeExp'], name = c))
fig.show()
这篇关于为什么 go.Scatter 打印额外的行而 px.line 不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 go.Scatter 打印额外的行而 px.line 不是?
基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01