Home > Blockchain >  Plot a percentage from a decimal in Plotly
Plot a percentage from a decimal in Plotly

Time:06-27

I have a dataframe that I want to plot in a column chart. The dataframe shows percentages in decimal points (such as 0.9994400) and I would like to show them on my chart as 99.944%.

I've tried to change the axis of the chart multiple times, but the values always round up to 100%. How can I get the axis and hover numbers to show the decimal points?

For example, the first data point should show 99.944%, but it shows 100%.

My dataframe: df_uptime_percentage

Name Percentage
API 1 0.9994400
API 2 0.999914
API 3 0.999913
API 4 0.999925
API 5 0.999461

My plot script:

cf.go_offline()

fig = df_uptime_percentage.iplot(kind='bar', 
        yTitle='Percent Uptime',
        xTitle='API Endpoint',
        asFigure = True)
fig.update_layout(yaxis_tickformat = '%')
fig.update_layout(hovermode="x unified")


fig.iplot()

My plot output: enter image description here

My imported libraries:

import time
from dateutil.relativedelta import relativedelta
import math
import requests
import re
import json
import pandas as pd 
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *
init_notebook_mode()
%matplotlib inline

CodePudding user response:

I am not sure what is causing the numbers to be rounded, but if you add the y-axis tick marks to the percent table and add the number of digits, the axis will have two decimal places, and the hover text will also have two decimal places.

import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *

cf.go_offline()

fig = df.iplot(kind='bar', 
        yTitle='Percent Uptime',
        xTitle='API Endpoint',
        asFigure=True)
fig.update_layout(yaxis_tickformat='.3%')
fig.update_layout(hovermode="x unified")

fig.iplot()

enter image description here

CodePudding user response:

Didn't quite catch where in your code you imported the numbers from your data frame to be used for your plot, but from how you describe your issue, I'm thinking this has something to do with a floating-point error. I wrote some basic code to convert the value you got for API1:

x = 0.9994400
x = x*100
x = float("{:.2f}".format(x))

print(x)

This code prints 99.94. If you were to change the 3rd line in the code to

x = float("{:.3f}".format(x))

it would give you 99.944.

Hope this helps!

  • Related