我正在尝试绘制雷达图,我希望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以字符串形式读取数组而不必添加额外的文本? (实际剧情更加拥挤)。
答案 0 :(得分:2)
因此,这里发生的是,推断出角轴的type
是linear
而不是category
,因为所有字符串都只包含数字。如果添加非数字字符串,则会以另一种方式哄骗推断。
您可以通过以下方式显式设置plotly.express
和plotly.graph_objects
方法的类型
fig.update_polars(angularaxis_type="category") # chaining-friendly
或
fig.layout.polar.angularaxis.type="category" # more imperative style
答案 1 :(得分:0)
如果您不介意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'] = ['<i>'+elem+'</i>' for elem in df['theta']]
至df['thetaText'] = ['<i>'+str(elem)+'</i>' for elem in df['theta']]