python - Plotly:如何使用文本模板的空间来自动化 y 轴?

标签 python plotly plotly-python

我尝试弄清楚如何使用文本模板绘制此条形图。无需切割它们,还能保持 y 轴动态。感谢您的想法!

import plotly.express as px

df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
df.lifeExp = df.lifeExp/100
fig = px.bar(df, y='lifeExp', x='country', text='lifeExp')
fig.update_traces(texttemplate='%{text:.2%}', textposition='outside')
fig.update_layout(uniformtext_minsize=20, uniformtext_mode='show')
plotly.io.write_image(fig, file='bartest.png', format='png')

enter image description here

最佳答案

设置 uniformtext_minsize=20 会让你的人物看起来很拥挤。因此,我实际上会选择:

,而不是 fig.update_traces(texttemplate='%{text:.2%}', textposition='outside')
fig.update_traces(texttemplate='%{text:.2%}', textposition='inside')
fig.update_layout(uniformtext_minsize=12, uniformtext_mode='show')

图 1

enter image description here

Plotly 将 y 轴的大小调整为条形的大小,而不是随后添加到其中的文本的大小,这样您就可以防止剪切文本时出现任何问题。如果出于某种原因您希望将文本元素保留在条形上方,则必须相应地调整 y 轴,例如:

fig.update_yaxes(range=[0, max(df.lifeExp)*1.2])

但是正如您所看到的,您必须将 uniformtext_minsize 设置为一个不切实际的低数字,以使文本元素可读:

图 2

enter image description here

图 1 的完整代码

import plotly.express as px

df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
df.lifeExp = df.lifeExp/100
fig = px.bar(df, y='lifeExp', x='country', text='lifeExp')
fig.update_traces(texttemplate='%{text:.2%}', textposition='inside')
fig.update_layout(uniformtext_minsize=11, uniformtext_mode='show')
# plotly.io.write_image(fig, file='bartest.png', format='png')


fig.show()

图 2 的完整代码

将plotly.express导入为px

df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
df.lifeExp = df.lifeExp/100
fig = px.bar(df, y='lifeExp', x='country', text='lifeExp')
fig.update_traces(texttemplate='%{text:.2%}', textposition='outside')
fig.update_layout(uniformtext_minsize=5, uniformtext_mode='show')
# plotly.io.write_image(fig, file='bartest.png', format='png')
fig.update_yaxes(range=[0, max(df.lifeExp)*1.2])

fig.show()

关于python - Plotly:如何使用文本模板的空间来自动化 y 轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66535691/

相关文章:

python - 如何使 Plotly 饼图始终大小相同

python - 使用 Selenium 检查所有复选框

python - 如何使用 LABEL_COLUMN 作为连续基列修改 tensorflow 示例 "census"?

python - 从 sqlalchemy 转储 csv

python - 可迭代 float ?

python - 为 plotly 人物的每个方面添加痕迹

python - 堆积条形图返回意外输出(Python,plotly)

python - Plotly:如何使子图的 x 和 y 轴标题变大?

python - 使用 plotly 修改轴范围

Python Plotly,如何去除背景水平线?