How can I add the date axis to my plotly graph object figure?

Asked by Kamden Patterson on
Tags: object
6 Answers

Answer by Jayceon Sweeney

Any kind of cartesian chart can be placed on date axes, for example this bar chart of relative stock ticker values.,Time series can be represented using either plotly.express functions (px.line, px.scatter, px.bar etc) or plotly.graph_objects charts objects (go.Scatter, go.Bar etc). For more examples of such charts, see the documentation of line and scatter plots or bar charts., Support Community Support Documentation ,For financial applications, Plotly can also be used to create Candlestick charts and OHLC charts, which default to date axes.

# Using plotly.express
import plotly.express as px

df = px.data.stocks()
fig = px.line(df, x='date', y="GOOG")
fig.show()

Source: https://plotly.com/python/time-series/


Answer by Giavanna Choi

Second, there are two keys in the figure dictionary: layout and data. In layout, you define the looks of your graph like the typography, titles, and axes. In the data key, you set the values and information of the traces you'll be plotting. That could be something like [1, 2, 3] for X, [5, 3, 9] for Y and bar chart type.,Whenever you add a trace to a graph, you can assign the right color to the marker_color attribute by getting it from the COLOR_MAPPER dictionary.,First, making a graph in Plotly is essentially populating a Python dictionary. This dictionary is usually referred to as figure.,There are three things you need to know about the inner workings of Plotly:

The code for making a graph using the Figure Constructor looks as follows:

import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns = np.random.normal(0.01, 0.2, 100)price = 100 * np.exp(returns.cumsum())time = np.arange(100)# Generate graph using Figure Constructorlayout = go.Layout(    title="Historic Prices",    xaxis_title="time",    yaxis_title="price")fig = go.Figure(    data=go.Scatter(x=time, y=price),    layout=layout)   fig.show()

Here's how you can do it:

import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns = np.random.normal(0.01, 0.2, 100)price = 100 * np.exp(returns.cumsum())time = np.arange(100)layout = go.Layout(    title="Historic Prices",    plot_bgcolor="#FFF",  # Sets background color to white    xaxis=dict(        title="time",        linecolor="#BCCCDC",  # Sets color of X-axis line        showgrid=False  # Removes X-axis grid lines    ),    yaxis=dict(        title="price",          linecolor="#BCCCDC",  # Sets color of Y-axis line        showgrid=False,  # Removes Y-axis grid lines        ))fig = go.Figure(    data=go.Scatter(x=time, y=price),    layout=layout)   fig.show()

Here's how you can do that using Plotly:

import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns_A = np.random.normal(0.01, 0.2, 100)returns_B = np.random.normal(0.01, 0.2, 100)returns = np.append(returns_A, returns_B)prices_A = 100 * np.exp(returns_A.cumsum())prices_B = 100 * np.exp(returns_B.cumsum())prices = np.append(prices_A, prices_B)companies = ["A"] * 100 + ["B"] * 100time = np.append(np.arange(100), np.arange(100))df = pd.DataFrame({    "company": companies,    "time": time,    "price": prices,    "returns": returns})# Build graphCOLORS_MAPPER = {    "A": "#38BEC9",    "B": "#D64545"}layout = go.Layout(    title="Performance of A vs. B",        plot_bgcolor="#FFFFFF",    barmode="stack",    xaxis=dict(        domain=[0, 0.5],        title="time",        linecolor="#BCCCDC",    ),    yaxis=dict(        title="price",        linecolor="#BCCCDC"    ),    xaxis2=dict(        domain=[0.6, 1],        title="returns",        linecolor="#BCCCDC",    ),    yaxis2=dict(        anchor="x2",        linecolor="#BCCCDC"    ))data = []for company,col in COLORS_MAPPER.items():    time = df.loc[df.company == company, "time"]    price = df.loc[df.company == company, "price"]    returns = df.loc[df.company == company, "returns"]    line_chart = go.Scatter(        x=time,        y=price,        marker_color=col,  # Defines specific color for a trace        legendgroup=company,  # Groups traces belonging to the same group in the legend         name=company    )    histogram = go.Histogram(        x=returns,        marker_color=col,  # Defines specific color for a trace        legendgroup=company,  # Groups traces belonging to the same group in the legend         xaxis="x2",         yaxis="y2",        showlegend=False    )    data.append(line_chart)    data.append(histogram)fig = go.Figure(data=data, layout=layout)fig.show()

A spike line is a vertical or horizontal line that appears when hovering on data. It's useful for comparing values in line charts and scatter plots. This is how you can add those using Plotly:

import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns_A = np.random.normal(0.01, 0.2, 100)returns_B = np.random.normal(0.01, 0.2, 100)returns = np.append(returns_A, returns_B)prices_A = 100 * np.exp(returns_A.cumsum())prices_B = 100 * np.exp(returns_B.cumsum())prices = np.append(prices_A, prices_B)companies = ["A"] * 100 + ["B"] * 100time = np.append(np.arange(100), np.arange(100))df = pd.DataFrame({    "company": companies,    "time": time,    "price": prices,    "returns": returns})# Build graphlayout = go.Layout(    title="Performance of A vs. B",        plot_bgcolor="#FFFFFF",    hovermode="x",    hoverdistance=100, # Distance to show hover label of data point    spikedistance=1000, # Distance to show spike    xaxis=dict(        title="time",        linecolor="#BCCCDC",        showspikes=True, # Show spike line for X-axis        # Format spike        spikethickness=2,        spikedash="dot",        spikecolor="#999999",        spikemode="across",    ),    yaxis=dict(        title="price",        linecolor="#BCCCDC"    ))data = []for company in ["A", "B"]:    time = df.loc[df.company == company, "time"]    price = df.loc[df.company == company, "price"]    returns = df.loc[df.company == company, "returns"]    line_chart = go.Scatter(        x=time,        y=price,        name=company    )    data.append(line_chart)fig = go.Figure(data=data, layout=layout)fig.show()

This is how you can apply those changes:

import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns_A = np.random.normal(0.01, 0.2, 100)returns_B = np.random.normal(0.01, 0.2, 100)returns = np.append(returns_A, returns_B)prices_A = 100 * np.exp(returns_A.cumsum())prices_B = 100 * np.exp(returns_B.cumsum())prices = np.append(prices_A, prices_B)companies = ["A"] * 100 + ["B"] * 100time = np.append(np.arange(100), np.arange(100))df = pd.DataFrame({    "company": companies,    "time": time,    "price": prices,    "returns": returns})# Build graphlayout = go.Layout(    title="Performance of A vs. B",        plot_bgcolor="#FFFFFF",    legend=dict(        # Adjust click behavior        itemclick="toggleothers",        itemdoubleclick="toggle",    ),    xaxis=dict(        title="time",        linecolor="#BCCCDC",    ),    yaxis=dict(        title="price",        linecolor="#BCCCDC"    ))data = []for company in ["A", "B"]:    time = df.loc[df.company == company, "time"]    price = df.loc[df.company == company, "price"]    returns = df.loc[df.company == company, "returns"]    line_chart = go.Scatter(        x=time,        y=price,        name=company    )    data.append(line_chart)fig = go.Figure(data=data, layout=layout)fig.show(config={"displayModeBar": False, "showTips": False}) # Remove floating menu and unnecesary dialog box

Source: https://towardsdatascience.com/4-ways-to-improve-your-plotly-graphs-517c75947f7e


Answer by Charlotte Hoffman

Plotting Financial Data Chart with Plotly Python,Plotting Financial Data Chart with Plotly Python GitHub repository., Plotting Financial Data Chart with Plotly Python Library for Jupyter Notebook ,Refinitiv Eikon Data API page on the Refinitiv Developer Community website.

    	
            import plotly.express as px
 
fig = px.line(x=["a","b","c"], y=[1,3,2], title="sample figure")
fig.show() 

        
        Copy
    

Source: https://developers.refinitiv.com/en/article-catalog/article/plotting-financial-data-chart-with-plotly-python-on-classic-jupy


Answer by Galilea Austin

Visualize univariate distributions with histograms, box-and-whisker or violin plots:,Our main goal with Plotly Express was to make it easier to use Plotly.py for exploration and rapid iteration.,Plotly is a data visualization company that makes it easy to build, test, and deploy beautiful interactive web apps, charts and graphs—in any programming language.,Plotly’s Dash puts AI & ML in the hands of business users

Plotly Express is a new high-level Python visualization library: it’s a wrapper for Plotly.py that exposes a simple syntax for complex charts. Inspired by Seaborn and ggplot2, it was specifically designed to have a terse, consistent and easy-to-learn API: with just a single import, you can make richly interactive plots in just a single function call, including faceting, maps, animations, and trendlines. It comes with on-board datasets, color scales and themes, and just like Plotly.py, Plotly Express is totally free: with its permissive open-source MIT license, you can use it however you like (yes, even in commercial products!). Best of all, Plotly Express is fully compatible with the rest of Plotly ecosystem: use it in your Dash apps, export your figures to almost any file format using Orca, or edit them in a GUI with the JupyterLab Chart Editor!

If you’re the TL;DR type, just pip install plotly and head on over to our walkthrough notebook or gallery or reference documentation to start playing around, otherwise read on for an overview of what makes Plotly Express special. If you have any feedback or want to check out the code, it’s all up on Github.

pip install plotly

Source: https://medium.com/plotly/introducing-plotly-express-808df010143d


Answer by Aydin Hayden

Now let’s plot! Cufflinks conviniently connects plotly to the iplot method in my dataframe. Let’s plot the occurence of each factor in a bar chart:,Now let’s look at incidents over time. I’m gonna transform the date column into an actual date object so that plotly is able to graph it in a time series. In addition, we want to make sure that the df is sorted by date:,Let’s look at the contributing factors of vehicle collisions. The factors are inconveniently divided into 5 columns, however pandas’ concat method should help us concatenate them into one:,Data Visualization with Plotly and Pandas

import pandas as pd
import numpy as np
import matplotlib
import cufflinks as cf
import plotly
import plotly.offline as py
import plotly.graph_objs as go

cf.go_offline() # required to use plotly offline (no account required).
py.init_notebook_mode() # graphs charts inline (IPython).

Source: https://dev.socrata.com/blog/2016/02/02/plotly-pandas.html