简体   繁体   中英

Using custom functions to format display of values in plotly

I am writing a small web-app to display prices over time for certain items in a game. The prices are integers but I want to format them to how the in game currency is displayed. This is the function I am using. It takes an integer and returns a string.

def copper_to_price(copper): # Converts copper int to a normal price
copper = int(copper)
s, c = divmod(copper, 100)
g, s = divmod(s, 100)
if g == 0:
    if s == 0:
        return '{}c'.format(c)
    else:
        return '{}s{}c'.format(s, c)
else:
    return '{}g{}s{}c'.format(g, s, c)

I am plotting these prices with plotly and want to have the y-axis ticks and y value hover text to be formatted with my function.

With plotly you can specify an y-axis tick formatter using tickformat but it seems you can only specify predefined formatting options and cannot pass your own custom formatting function.

It is also possible to specify your own tick values using tickvals and replace the text of these values with ticktext . I could specify my own y values and then format it with my function and return that as my ticktext but then I would have to generate my own y value ticks that will fit my data. I haven't found any good python scripts that can generate y tick values that will fit your data well.

How can I display my y values formatted with my own function using plotly?

You already described the way to go. Why not take your plotting data, extract minimum and maximum values, use tv = np.arrange(min, max, 0.25) to create the sequence of tickvals and then use ticktext = [copper_to_price(member) for member in tv] to format them. When you are done with that, just set the corresponding layout options

layout = go.Layout(
    yaxis=dict(
        tickmode='array',
        tickvals=tv,
        ticktext=tt
    )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM