如何使用 px.bar() 在堆积条形图中显示百分比值?
How to display percentages values in stacked bar chart using px.bar()?
需要在数值的同时显示%符号。请检查下面的附图。我有什么办法可以用数值添加 % 符号吗?
# 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()
您可以使用:
fig.for_each_trace(lambda t: t.update(texttemplate = t.texttemplate + ' %'))
并得到:
完整代码:
# 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()
需要在数值的同时显示%符号。请检查下面的附图。我有什么办法可以用数值添加 % 符号吗?
# 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()
您可以使用:
fig.for_each_trace(lambda t: t.update(texttemplate = t.texttemplate + ' %'))
并得到:
完整代码:
# 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()