如何在python的一列中插入2个图
Posted
技术标签:
【中文标题】如何在python的一列中插入2个图【英文标题】:How to insert 2 graphs in one column on python 【发布时间】:2021-12-04 07:14:20 【问题描述】:现在我正在学习 python。我的第一个问题是“如何在 python 的一列中插入 2 个图表”。请帮帮我
我的代码是:使用情节。
fig0.update_traces(mode='markers', marker_line_width=1, marker_size=5)
fig0.update_layout(title='Confirmed case by gender',yaxis_zeroline=False, xaxis_zeroline=False)
fig0.show()
fig1 = px.line(timegender, x='date', y='deceased', color='sex', markers = True)
fig1.update_traces(mode='markers', marker_line_width=1, marker_size=5)
fig1.update_layout(title='Deceased case by gender',yaxis_zeroline=False, xaxis_zeroline=False)
fig1.show()
【问题讨论】:
两张图一栏?很难解释这一点 - 1. 一个活动仪表板,即 dash 2. 使用同一轴的多个跟踪,其中列是 xaxis 上的类别,即一个图中的多个跟踪 3. 多组轴,即子地块 【参考方案1】: 您显然在按性别划分 COVID 病例。已获取数据来证明这一点 绘图的关键是结构化数据框-
使 sex 列包含 male 或 female
使 measure 列包含 cases 或 deaths
import requests
import io
import pandas as pd
import plotly.express as px
# fmt: off
# sex disaggregation data
dfsda = pd.read_csv(io.StringIO(requests.get("https://globalhealth5050.org/?_covid-data=datasettable&_extype=csv").text))
# case / death data
dfall = pd.read_csv(io.StringIO(
requests.get("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv").text))
dfall["date"] = pd.to_datetime(dfall["date"])
dfcc = pd.read_html("https://www.iban.com/country-codes")[0]
# data prep - join three data sources
df = dfsda.merge(dfcc, left_on="Country code", right_on="Alpha-2 code").merge(
dfall, left_on="Alpha-3 code", right_on="iso_code"
)
# calc split between male & female
df2 = (
df.loc[:,['Cases (% female)', 'Deaths (% female)', 'Alpha-2 code', 'Alpha-3 code', 'location', 'date', 'total_cases', 'total_deaths']]
.dropna()
.assign(
**"Cases (% female)": lambda d: d["Cases (% female)"].str.strip("%").astype(float) / 100,
"Deaths (% female)": lambda d: d["Deaths (% female)"].str.strip("%").astype(float) / 100,
"cases_male": lambda d: d["total_cases"] * (1 - d["Cases (% female)"]),
"cases_female": lambda d: d["total_cases"] * (d["Cases (% female)"]),
"deaths_male": lambda d: d["total_deaths"] * (1 - d["Deaths (% female)"]),
"deaths_female": lambda d: d["total_deaths"] * (d["Deaths (% female)"]),
)
)
# fmt: on
# structure for plotting
df3 = (
pd.wide_to_long(
df2,
i=["Alpha-3 code", "location", "date"],
stubnames=["cases", "deaths"],
j="sex",
sep="_",
suffix=r"\w+",
)
.loc[:, ["cases", "deaths"]]
.stack()
.reset_index()
.rename(columns="level_4": "measure", 0: "value")
)
# finally plot
px.line(
df3.loc[df3["Alpha-3 code"].eq("USA")],
x="date",
y="value",
color="sex",
markers=True,
facet_col="measure",
).update_yaxes(matches=None).show()
px.line(
df3.loc[df3["Alpha-3 code"].eq("USA")],
x="date",
y="value",
color="sex",
markers=True,
facet_row="measure",
).update_yaxes(matches=None).show()
【讨论】:
以上是关于如何在python的一列中插入2个图的主要内容,如果未能解决你的问题,请参考以下文章
如何在 python 的另一列中的字符串值中从数据框中的一列中搜索字符串?