Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple text labels from DataFrame columns in Plotly

The goal is to plot some data using plotly where the text param contains multiple columns.

Here is my DataFrame:

import pandas as pd
import numpy as np
import plotly as py
import plotly.graph_objs as go

np.random.seed(1)
df = pd.DataFrame({'Mean Age': np.random.randint(40,60,10),
                   'Percent': np.random.randint(20,80,10),
                   'Number Column': np.random.randint(100,500,10)},
                  index=list('ABCDEFGHIJ'))

df.index.name = 'Text Column'
df = df.sort_values('Mean Age')

Here is an example of how I plotted the data with text from one column to show on hover:

# trace for Percent
trace0 = go.Scatter(
    x = df.index,
    y = df['Percent'],
    name = 'Percent',
    text = df['Mean Age'], # text to show on hover from df column
    mode = 'lines+markers',
    line = dict(
        color = ('rgb(0,0,255)'), # blue
        width = 4)
)

layout = dict(title = 'Test Plot',
             xaxis = dict(title = 'Text Column'),
             yaxis = dict(title = 'Percent'),
              )

data = [trace0]
fig = dict(data=data, layout=layout)

py.offline.plot(fig, filename = 'Test_Plot.html')

I am looking to add another column's data to the text param. I can accomplish this by doing some list comprehensions but is there an easier/more efficient way to do this?

I am looking for an output similar to what is below but in a more efficient way than using list comprehension:

# column values to list
num = list(df['Number Column'])
age = list(df['Mean Age'])


# trace for Percent
trace0 = go.Scatter(
    x = df.index,
    y = df['Percent'],
    name = 'Percent',
    # list comprehension to get the data to show
    text = [f'Number Column: {x}; Mean Age: {y}' for x,y in list(zip(num, age))],
    mode = 'lines+markers',
    line = dict(
        color = ('rgb(0,0,255)'), # blue
        width = 4)
)

layout = dict(title = 'Test Plot',
             xaxis = dict(title = 'Text Column'),
             yaxis = dict(title = 'Percent'),
              )

data = [trace0]
fig = dict(data=data, layout=layout)

py.offline.plot(fig, filename = 'Test_Plot_Output.html')
like image 385
It_is_Chris Avatar asked Jan 25 '19 15:01

It_is_Chris


People also ask

How do you add labels in plotly?

As a general rule, there are two ways to add text labels to figures: Certain trace types, notably in the scatter family (e.g. scatter , scatter3d , scattergeo etc), support a text attribute, and can be displayed with or without markers. Standalone text annotations can be added to figures using fig.

What is hover name in plotly?

The hover_name property controls which column is displayed in bold as the tooltip title. Here is an example that creates a scatter plot using Plotly Express with custom hover data and a custom hover name.

What is the difference between plotly and Plotly Express?

Overview. The plotly. express module (usually imported as px ) contains functions that can create entire figures at once, and is referred to as Plotly Express or PX. Plotly Express is a built-in part of the plotly library, and is the recommended starting point for creating most common figures.

Does plotly use SVG?

Each plotly trace type is primarily rendered with either SVG or WebGL, although WebGL-powered traces also use some SVG.


1 Answers

You could also do something along the lines of the following:

trace0 = go.Scatter(
    x = df.index,
    y = df['Percent'],
    name = 'Percent',
    # string concatenation in pandas
    # also the <br> puts the data on a new line in the hover text
    text = "Number Column: " + df["Number Column"].astype(str) + "<br>Mean Age: " + df["Mean Age"].astype(str),
    mode = 'lines+markers',
    line = dict(
        color = ('rgb(0,0,255)'),  # blue
        width = 4)
)
like image 162
Caleb Courtney Avatar answered Sep 30 '22 18:09

Caleb Courtney