【问题标题】:label pandas header with an index name用索引名称标记 pandas 标头
【发布时间】:2021-07-01 09:48:00
【问题描述】:

我尝试运行这段代码,用 plotly express 生成一个图。

import plotly.express as px

df = pd.DataFrame([[1,1,1,0,0], [1,1,1,0,1],
                   [1,1,0,1,0], [0,1,1,1,1]])

##example by plotly
#https://plotly.com/python/facet-plots/
#fig = px.line(df, facet_col="company", facet_col_wrap=2)

fig = px.area(df, facet_col_wrap=2) #works but not as expected
#fig = px.area(df,facet_col="???", facet_col_wrap=2) #should be the solution, but "???" is missing

fig.show(renderer="browser")

plolty (https://plotly.com/python/facet-plots/) 的示例有一个带标签的标题(“company”),它是用 facet_col 调用的。 id 不知道如何为我的 df 标头插入标签。我希望像 plotly 中的示例一样绘制数据框。

【问题讨论】:

    标签: pandas plotly


    【解决方案1】:

    您需要将您的数据框放入适当的结构中以进行 plotly express

    • unstack() 将列转换为索引中的行
    • reset_index() 做索引列,加上用set_index() 恢复原来的行索引
    • 现在你有了一个结构来使用px.line()的参数
    
    import plotly.express as px
    
    df = pd.DataFrame([[1,1,1,0,0], [1,1,1,0,1],
                       [1,1,0,1,0], [0,1,1,1,1]])
    
    px.area(df.unstack().to_frame().reset_index().set_index("level_0"), facet_col="level_1", facet_col_wrap=2)
    
    

    【讨论】:

      猜你喜欢
      • 2013-08-04
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      相关资源
      最近更新 更多