【问题标题】:What is the Plotly Graph_Objects equivalent of this Plotly_Express Code?这个 Plotly_Express 代码的 Plotly Graph_Objects 等价物是什么?
【发布时间】:2021-12-26 23:57:30
【问题描述】:

我有一个如下所示的数据框:

Date           Region         Rent

2014-10-01     Miami          1840

2014-10-01     Tampa          1340

...            ...            ...

当我使用这个 Plotly_Express 代码时,它会产生我想要的东西

fig = px.line(Zori_filtered, x='Date', y='Rent', color='RegionName')

#fig.write_html("d:/downloads/zori.html")

fig.show()

我想用 Graph_Objects 生成相同的图,以便我可以在另一个子图中附加具有相似数据的另一个图。

我不知道该怎么做。

谢谢

【问题讨论】:

  • 我的例子很奇怪。数据框如下所示: Date Region Rent 2014-10-01 Miami 1840 2014-10-01 Tampa 1340 2015-11-01 Tampa 1325
  • 链接的问题是关于条形图的,但同样的想法在这里也有效

标签: plotly


【解决方案1】:
  • 您没有提供示例数据,因此我从 kaggle 获取数据用于演示目的
  • Plotly Express 为每个 RegionName 生成一个跟踪,因此这是一个在列表理解中使用 pandas groupby() 的简单案例
go.Figure(
    [
        go.Scatter(name=g[0], x=g[1]["Date"], y=g[1]["Rent"])
        for g in Zori_filtered.groupby("RegionName")
    ]
)

包含数据源的完整代码

import kaggle.cli
import sys, requests
import pandas as pd
from pathlib import Path
from zipfile import ZipFile
import urllib
import plotly.express as px
import plotly.graph_objects as go

# fmt: off
# download data set
url = "https://www.kaggle.com/zillow/rent-index"
sys.argv = [sys.argv[0]] + f"datasets download {urllib.parse.urlparse(url).path[1:]}".split(" ")
kaggle.cli.main()
zfile = ZipFile(f'{urllib.parse.urlparse(url).path.split("/")[-1]}.zip')
dfs = {f.filename: pd.read_csv(zfile.open(f)) for f in zfile.infolist()}
# fmt: on

Zori_filtered = dfs["price.csv"]

# structure data from kaggle in same way as dataframe in question is structured
Zori_filtered = Zori_filtered.loc[Zori_filtered["Population Rank"].lt(11)].set_index(
    Zori_filtered.columns[0:6].tolist()
).stack().reset_index().rename(columns={"level_6":"Date",0:"Rent"})
Zori_filtered["Date"] = pd.to_datetime(Zori_filtered["Date"])

Zori_filtered["RegionName"] = Zori_filtered["County"]+"-"+Zori_filtered["City"]+" - " + Zori_filtered["State"]

px.line(Zori_filtered, x='Date', y='Rent', color='RegionName').show()

# the answer...
go.Figure(
    [
        go.Scatter(name=g[0], x=g[1]["Date"], y=g[1]["Rent"])
        for g in Zori_filtered.groupby("RegionName")
    ]
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2019-02-12
    • 2021-06-15
    • 1970-01-01
    相关资源
    最近更新 更多