为什么go.Scatter打印多余的行,而px.line不是? [英] Why is go.Scatter printing extra lines whereas px.line is not?

查看:124
本文介绍了为什么go.Scatter打印多余的行,而px.line不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的graph_objects代码-

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?)

推荐答案

如果没有适当的数据样本,我无法100%确定.但是,看来您的数据集的格式很长,在 continent_df.new_cases_smoothed 中有多个值,它们属于不同的内容.然后,您可以使用 go.Figure(go.Scatter(x = continent_df.date,y = continent_df.new_cases_smoothed))将所有这些值分配给单个跟踪.

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

但是,这里使用 px.line 通过使用 color ='continent'对各大洲进行分组来解决这一问题.因此,使值类别显示为唯一的痕迹.

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.

我们可以使用gapminder数据集(其结构与您的真实世界数据相似)来说明如何使用 fig.add_traces(go.Scatter()).关键是检索唯一的类别,子集数据并逐行添加组.与使用 px.line 相比,这可以给您带来更大的灵活性.

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.

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不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆