python - 如何使用 px.bar() 在堆积条形图中显示百分比值?

标签 python python-3.x plotly bar-chart plotly-python

需要与数值一起显示%符号。请检查下面的附图。有什么办法可以在数值上添加%符号吗?

# Import pandas library
import pandas as pd
 
# initialize list of lists
data = [['2017/2018', 'Renewable',21], ['2018/2019', 'Renewable',42], ['2019/2020', 'Renewable',75],
       ['2017/2018', 'Non-Renewable',79], ['2018/2019', 'Non-Renewable',58], ['2019/2020', 'Non-Renewable',25]]
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Year', 'Energy','Energy Mix %'])
 
# print dataframe.
df


fig = px.bar(df, x="Year", y="Energy Mix %", color="Energy", title="RENEWABLE ENERGY MIX",
             text_auto=True,template='plotly_dark')
fig.show()

enter image description here

最佳答案

您可以使用:

fig.for_each_trace(lambda t: t.update(texttemplate = t.texttemplate + ' %'))

并得到:

enter image description here

完整代码:

# Import pandas library
import pandas as pd
import plotly.express as px
# initialize list of lists
data = [['2017/2018', 'Renewable',21], ['2018/2019', 'Renewable',42], ['2019/2020', 'Renewable',75],
       ['2017/2018', 'Non-Renewable',79], ['2018/2019', 'Non-Renewable',58], ['2019/2020', 'Non-Renewable',25]]
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Year', 'Energy','Energy Mix %'])
 
fig = px.bar(df, x="Year", y="Energy Mix %", color="Energy", title="RENEWABLE ENERGY MIX",
             text_auto=True,template='plotly_dark')

fig.for_each_trace(lambda t: t.update(texttemplate = t.texttemplate + ' %'))

fig.show()

关于python - 如何使用 px.bar() 在堆积条形图中显示百分比值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71019236/

相关文章:

python - 牛顿重力模拟

python - 如何在字典中使用for循环

python - 使用 DictReader 从 csv 文件中获取第一条记录

python - 在 Snakemake 脚本中使用 argparse

plotly - jupyter-lab 中未显示动画绘图表达图

javascript - 在 Plotly.js 中禁用悬停

python - "Pythonic"就地替换列表中的一个或多个项目的方法

python-3.x - 在 Python 3 中将双反斜杠转换为单反斜杠

python - 在 anaconda3 中安装 openCV - Python.h : No such file or directory

r - 使用 R 绘图的重新样式按钮将颜色映射到变量上