【问题标题】:Plotly: Radar plot mistaking theta as int instead of stringPlotly:雷达图将 theta 误认为是 int 而不是 string
【发布时间】:2020-03-28 18:54:01
【问题描述】:

我正在尝试制作雷达图,并且我希望 theta 轴是字符串。他们应该是["01", "02", "03"]。但是,它们被 Plotly 读取为数字。

import pandas as pd
import plotly.express as px

df = pd.DataFrame(dict(
    r=[22, 6, 0],
    theta=["01", "02", "03"]))
fig = px.line_polar(df, r='r', theta='theta', line_close=True)
fig.update_traces(fill='toself')
fig.show()

但是,如果我将一些文本添加到数组中,它会被读取为字符串,并且我会获得我正在寻找的数字。

df = pd.DataFrame(dict(r=[22, 6, 0],
                       theta=["Code: 01", "Code: 02", "Code: 03"]))
fig = px.line_polar(df, r='r', theta='theta', line_close=True)
fig.update_traces(fill='toself')
fig.show()

如何让 Plotly 将数组作为字符串读取,而无需添加额外的文本? (实际的情节要拥挤得多)。

【问题讨论】:

    标签: python plotly plotly-python


    【解决方案1】:

    所以这里发生的情况是角轴的type 被推断为linear 而不是category,因为所有字符串都只包含数字。如果您添加一个非数字字符串,则会以另一种方式诱使推理。

    您可以显式设置plotly.expressplotly.graph_objects 方法的类型

    fig.update_polars(angularaxis_type="category") # chaining-friendly
    

    fig.layout.polar.angularaxis.type="category" # more imperative style
    

    【讨论】:

      【解决方案2】:

      如果您不介意一点 html 格式,任何 html 格式似乎都会强制将您的输入解释为文本。

      剧情:

      如您所见,我使用了斜体 <i>yourtext</i>,但任何 html 都应该可以。事实上,span 标记将使您的文本保持未格式化。

      代码:

      import pandas as pd
      import plotly.express as px
      
      df = pd.DataFrame(dict(r=[22, 6, 0], theta=['01','02','03']))
      
      df['thetaText'] = ['<i>'+elem+'</i>' for elem in df['theta']]
      
      fig = px.line_polar(df, r='r', theta='thetaText', line_close=True)
      fig.update_traces(fill='toself')
      fig.show()
      

      编辑:

      如果您想使用 [1,2,3] 作为 theta 的输入,只需更改 df['thetaText'] = ['&lt;i&gt;'+elem+'&lt;/i&gt;' for elem in df['theta']]df['thetaText'] = ['&lt;i&gt;'+str(elem)+'&lt;/i&gt;' for elem in df['theta']]

      【讨论】:

      • 代替斜体(或将数字包装在无用的&lt;span&gt; 中,在数字前面加上一个零宽度不间断空格(&amp;#xfeff;)可能有效吗?
      • @kthy 我没有测试它。你觉得会比'&lt;span&gt;'+elem+'&lt;/span&gt;'省力吗?
      猜你喜欢
      • 2010-11-13
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多