Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't figure out how to make my Plotly charts show whole numbers only

Tags:

python

plotly

image of plotly chart

Hello, I'm really struggling to figure out how to format the axes on this chart. I've gone through the documentation and tried all sorts of different formatting suggestions from here and elsewhere but really not getting it. As you can see, the bottom chart has a .5 number, I want that to be skipped altogether and only have whole numbers along the axis.

I've seen ,d as a tickformat option to do this in about every answer, but I can't get that to work or I'm not seeing how to apply it to the second chart.

Can anyone with some Plotly charting experience help me out?

Here's the pertinent code:

def create_chart():
#Put data together into an interactive chart
fig.update_layout(height=500, width=800, yaxis_tickprefix = '$', hovermode='x unified', xaxis_tickformat =',d',
                  template=symbol_template, separators=".", title_text=(df.columns[DATA_COL_1]) + " & Units 2015-2019"
                  )
like image 218
Mulcch Avatar asked Sep 06 '25 23:09

Mulcch


1 Answers

I believe what is happening is that the xaxis_tickformat parameter is affecting only the first subplot, but not the second one. To modify the formatting for each subplot, you can pass a dictionary with the tickformat parameter to yaxis, yaxis2, .... and so on for however many subplots you have (in your case, you only have 2 subplots).

import pandas as pd
from plotly.subplots import make_subplots
import plotly.graph_objects as go

## recreate the df 
df = pd.DataFrame({'Year':[2015,2016,2017,2018,2019],
    'Sales':[8.8*10**7,8.2*10**7,8.5*10**7,9.1*10**7,9.6*10**7],
    'Units':[36200,36500,36900,37300,37700]})

def create_chart():
    #Put data together into an interactive chart
    fig = make_subplots(rows=2, cols=1)
    fig.add_trace(go.Scatter(
        x=df.Year, 
        y=df.Sales, 
        name='Sales',
        mode='lines+markers'
    ), row=1, col=1)

    fig.add_trace(go.Scatter(
        x=df.Year, 
        y=df.Units, 
        name='Units',
        mode='lines+markers'
    ), row=2, col=1)

    fig.update_layout(
        title_x=0.5,
        height=500, 
        width=800, 
        yaxis_tickprefix = '$', 
        hovermode='x unified', 
        xaxis_tickformat =',d',
        ## this will change the formatting for BOTH subplots
        yaxis=dict(tickformat ='d'),
        yaxis2=dict(tickformat ='d'),
        # template=symbol_template, 
        separators=".", 
        title={
            'text':"MCD Sales & Units 2015-2019",
            'x':0.5
        }
    )
    fig.show()

create_chart()

enter image description here

like image 178
Derek O Avatar answered Sep 09 '25 13:09

Derek O