Home > Net >  plotly express | change tick units on y axis
plotly express | change tick units on y axis

Time:09-24

I want to add units to my yaxis of my bar chart. Im using plotly.express for that but didnt found a working solution inside the documentation. text_auto() and fig.update_layout() are not working for me right now. (Tried that thread without success -> How it looks now without units for eacht tick.

import json
import requests
from operator import itemgetter
import plotly.express as px

#hyperlinks = xaxis with description and link to the game
#times = yaxis total playtime (<- where i want to use "xx.xh")
#titles = simple hover text
df = {
    "x" : hyperlinks,
    "y" : times,
    "titles" : titles,
    }   

fig = px.bar(
    df,
    x="x", 
    y="y",
    hover_data=["titles"],
    color="y",
    color_continuous_scale="Plotly3_r",
    title=f"Top 30 games with most playtime",
    text_auto=".h",
    labels={"y" : "entire playtime of steam games"},
    )

fig.update_layout(
    yaxis={
        "tickformat" : '.h'
        }
    )
fig.show()
fig.write_html("My_most_played_games.html")

CodePudding user response:

I have generated some random values for the example.

Since recently you can have access to figure parameters of plotly using fig.full_figure_for_development() from there you can extract element to check where plotly added ticks and regenerate them adding to them any string you want

import plotly.express as px
import numpy as np
#hyperlinks = xaxis with description and link to the game
#times = yaxis total playtime (<- where i want to use "xx.xh")
#titles = simple hover text
df = {
    "x" : ['black desert', 'arma 3', 'borderland 2', 'Cyberpunk'],
    "y" : [420, 350, 310, 180],
    "titles" : ['black desert', 'arma 3', 'borderland 2', 'Cyberpunk'],
    }   

fig = px.bar(
    df,
    x="x", 
    y="y",
    hover_data=["titles"],
    color="y",
    color_continuous_scale="Plotly3_r",
    title=f"Top 30 games with most playtime",
    text_auto=".h",
    labels={"y" : "entire playtime of steam games"},
    )

# Important part to recover infor from the figure
full_fig = fig.full_figure_for_development()  # recover data from figure
range_vl = full_fig.layout.yaxis.range  # get range of y axis
distance_tick = full_fig.layout.yaxis.dtick  # get distance between ticks

number_ticks = range_vl[1]//full_fig.layout.yaxis.dtick   1 # calculate number of ticks of your figure

tick_vals = [range_vl[0] distance_tick*num for num in range(int(number_ticks))] # generate your ticks
tick_text = [f"{val} h" for val in tick_vals] #generate text for your ticks

fig.update_layout(
    # set tick mode to array, tickvals to your vals calculated and tick text  to the text genrated
    yaxis={"tickmode":"array","tickvals":tick_vals, "ticktext": tick_text}
        
    )
fig.show()

enter image description here

  • Related