【问题标题】:Plotly scatterplot legends not displaying legend title, but with = sign for each color绘制散点图图例不显示图例标题,但每种颜色都有 = 符号
【发布时间】:2021-12-02 14:45:37
【问题描述】:

Plotly 拒绝按应有的方式显示图例。就我而言,颜色由数据点的“名称”决定。图例显示 Name=[name of the datapoint] 而不是为图例提供标题“名称”。

看起来像上图,但应该是这样的:

像“物种”标题一样,标题“名称”应该显示在我的案例中。有什么帮助吗?

【问题讨论】:

    标签: python pandas plotly jupyter google-colaboratory


    【解决方案1】:
    • 您没有包含数据或代码来生成绘图
    • 我来自 kaggle 并使用了px.scatter(dfs["Pokemon.csv"], x="Attack", y="Defense", color="Name"),它可以根据需要生成图形
    • 情节版本:'5.3.1'
    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
    
    # fmt: off
    # download data set
    url = "https://www.kaggle.com/abcsds/pokemon"
    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
    
    px.scatter(dfs["Pokemon.csv"], x="Attack", y="Defense", color="Name")
    
    

    【讨论】:

      【解决方案2】:

      如果没有可重现的示例,很难准确判断这里发生了什么。据我所知,px.scatter 的正确应用不应该呈现您正在显示的结果。至少对于较新版本的 Plotly 来说不是。但在任何一种情况下,为了获得充分的灵活性,您都可以运行以下两行来插入图例标题,并仅显示出现在 '=' 之后的每个图例元素的文本:

      fig.for_each_trace(lambda t: t.update(name=t.name.split("=")[-1]))
      fig.update_layout(legend_title_text = '<b>your title</b>')
      

      情节 1 - 修正前:

      情节 2 - 修正后:

      完整代码:

      import plotly.graph_objects as go
      import plotly.express as px
      
      # data
      df = px.data.iris()
      
      # adjust data to reproduce the problem
      df['species'] = ['species=' + s for s in df['species']]
      
      # build figure
      fig = px.scatter(df, x='petal_length', y = 'petal_width', color = 'species')
      
      # change legend entries
      fig.for_each_trace(lambda t: t.update(name=t.name.split("=")[-1]))
      
      # edit title and show figure
      fig.update_layout(legend_title_text = '<b>Custom title</b>')
      fig.show()
      

      【讨论】:

      • 你是对的,它不应该呈现它为我所做的那样。我通过在我的 colab 环境中使用“!pip install plotly --upgrade”进行升级来修复它。现在可以正常使用了,谢谢!
      • @makssyz 不客气!请考虑将其中一项建议标记为已接受的答案。也请考虑对任何有帮助的帖子进行投票。
      猜你喜欢
      • 2019-05-25
      • 2018-09-04
      • 1970-01-01
      • 2014-10-12
      • 2016-07-19
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      相关资源
      最近更新 更多