我有一个堆叠的水平条,我希望为每个轨迹定义的文本放置在相应条的中心。我找不到不使用注释的情况下设置它的属性,但我想为每条轨迹使用“文本”并且能够对齐它。
我正在使用 Plotly 3.4.1 和 Jupyter(Plotly 离线)。 找不到任何关于如何执行此操作的文档,除了尝试使用注释来执行此操作,如果我想查明一个显式坐标,这看起来是一个更合适的解决方案。我想要的是一个更简单的东西(类似于“align”:“center”),但是在 go.Bar 下找不到任何属性
只希望“80”、“20”出现在中间而不是靠右对齐
from plotly.offline import iplot, plot, init_notebook_mode
import plotly.graph_objs as go
def getStackedSentimentHbar():
trace0 = go.Bar(
y=["A","B"],
x=[20,80],
orientation = 'h',
text=["20","80"],
textposition="inside",
hoverinfo = "none",
)
trace1 = go.Bar(
y=["A","B"],
x=[80,20],
orientation = 'h',
text=["80","20"],
textposition="inside",
hoverinfo = "none",
)
data = [trace0,trace1]
layout = go.Layout(
barmode='stack',
showlegend=False,
xaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
ticks='',
showticklabels=False
),
yaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
ticks='',
showticklabels=True
),
margin = dict(
l = 200,
r = 50,
b = 50,
t = 50,
pad = 10
),
font=dict(
family='Heebo',
size=18,
color='#000000'
)
)
fig = go.Figure(data=data, layout=layout)
return fig
init_notebook_mode()
fig = getStackedSentimentHbar()
iplot(fig)
最佳答案
据我所知,Plotly 中没有这样的参数,但我们总是可以破解 Plotly :)
让我们复制所有的 x 和 y 值,但保留 text
原样。
在下面的代码中有两个函数,getStackedSentimentHbar
和 getStackedSentimentHbarCentered
。第一个返回原始图,第二个返回带有(几乎)居中标签的图。
from plotly.offline import iplot, plot, init_notebook_mode
import plotly.graph_objs as go
LAYOUT = go.Layout(
barmode='stack',
showlegend=False,
xaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
ticks='',
showticklabels=False
),
yaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
ticks='',
showticklabels=True
),
margin = dict(
l = 200,
r = 50,
b = 50,
t = 50,
pad = 10
),
font=dict(
family='Heebo',
size=18,
color='#000000'
)
)
def getStackedSentimentHbar(values):
data = []
for i, x in enumerate(values['x']):
trace = go.Bar(
x=x,
y=values['y'][i],
orientation='h',
text=x,
textposition='inside',
hoverinfo = 'none',
)
data.append(trace)
fig = go.Figure(data=data, layout=LAYOUT)
return fig
def getStackedSentimentHbarCentered(values):
data = []
for i, x in enumerate(values['x']):
trace = go.Bar(
x=[int(i / 2) for i in x * 2],
y=values['y'][i] * 2,
orientation = 'h',
text=x,
textposition='inside',
hoverinfo = 'none'
)
data.append(trace)
fig = go.Figure(data=data, layout=LAYOUT)
return fig
values = {'x': [[20, 80], [80, 20]],
'y': [['A', 'B'], ['A', 'B']]}
init_notebook_mode()
fig = getStackedSentimentHbarCentered(values)
iplot(fig)
关于python - 如何将跟踪文本对齐到堆叠水平条形图中的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53856826/