단일 그래프의 여러 데이터 프레임에 대해 플롯을 사용하여 꺾은 선형 차트를 그리려고합니다. 내 코드는 다음과 같습니다.
import plotly.express as px
labels=category_names[:10]
for category in category_names[:10]:
df_b=df1[df1['Country/Region']==category]
fig=px.line(df_b, x="Date", y="Confirmed",labels="Country/Region")
print(category)
fig.show()
그러나 위의 코드를 사용하여 for 루프의 마지막 반복에 대한 선 그래프를 얻을 수 있습니다.
전류 출력 :
원하는 출력 :
친절하게 코드를 도와주세요!
Using plotly.express
with px.line()
, you shouldn't have to use a for loop
at all to output multiple lines in a single figure as long as your dataset is of a long
format. You might be confusing this approach to using a for loop
and fig.add_figure()
, which is arguably better suited for data of a wide
format where you would have countries as column names, time as index, and a value of a single category in your dataframe.
Without a proper data sample it's not easy to tell with a 100% certainty what your issue is. But it seems to me that your data structure matches the structure of px.data.gapminder()
country continent year lifeExp pop gdpPercap iso_alpha iso_num
0 Afghanistan Asia 1952 28.801 8425333 779.445314 AFG 4
1 Afghanistan Asia 1957 30.332 9240934 820.853030 AFG 4
2 Afghanistan Asia 1962 31.997 10267083 853.100710 AFG 4
3 Afghanistan Asia 1967 34.020 11537966 836.197138 AFG 4
4 Afghanistan Asia 1972 36.088 13079460 739.981106 AFG 4
So I'll provide an answer based on that and you can try and sort it out from there. Unless you're willing to share a complete data sample and code snippet, of course.
Plot:
Complete code:
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
# sample dataset from plotly express
df = px.data.gapminder()
# Filter and pivot dataset for each country,
# and add lines for each country
fig = go.Figure()
for c in df['country'].unique()[:3]:
dfp = df[df['country']==c].pivot(index='year', columns='country', values='pop')
fig.add_traces(go.Scatter(x=dfp.index, y=dfp[c], mode='lines', name = c))
fig.show()
이 스 니펫이하는 일은 소스를 다음과 같이 고유 한 카테고리별로 하위 집합으로 만드는 것입니다.
country continent year lifeExp pop gdpPercap iso_alpha iso_num
564 Germany Europe 1952 67.5 69145952 7144.114393 DEU 276
565 Germany Europe 1957 69.1 71019069 10187.826650 DEU 276
566 Germany Europe 1962 70.3 73739117 12902.462910 DEU 276
567 Germany Europe 1967 70.8 76368453 14745.625610 DEU 276
568 Germany Europe 1972 71.0 78717088 18016.180270 DEU 276
... df[df['country']=='Germany'].pivot(index='year', columns='country', values='pop')
다음을 얻기 위해 해당 데이터 세트를 피벗합니다 .
country Germany
year
1952 69145952
1957 71019069
1962 73739117
1967 76368453
1972 78717088
1977 78160773
1982 78335266
1987 77718298
1992 80597764
1997 82011073
2002 82350671
2007 82400996
... 그런 다음을 사용하여 해당 데이터를 플롯 그림에 추가합니다 fig.add_traces()
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다