Search code examples
pythonpandasplotlyfigure

Python Anaconda 3.6 plotly module using Figure


can't seem to have this working:

import plotly.offline as pyo
from plotly.graph_objs import *
import plotly.plotly as py
import pandas as pd
from pandas import DataFrame

pyo.offline.init_notebook_mode() 


trace1 = {'type' : 'scatter',
          'x' : [1,2,3,4,5,6,7,8,9],
          'y' : [1,2,3,4,5,6,7,8,9],
          'name' : 'trace1',
          'mode' : 'lines'}

layout = {'title' : 'my first plotly chart',
          'xaxis' : {'X Values'},
          'yaxis' : {'Y Values'}        
          }

data = Data([trace1])

fig = Figure(data = data, layout = layout)

python dtates that Data in depreciated, and asks me to use something else, but I can't seem to figure it out.


Solution

  • Looks like you missed command to plot after creating figure. And Data([trace1]) looking incorrectly for my opinion. So if you want create a simple scatter plot using Python3, you can do it in two ways (and give the same result).
    1.First way:

    # Import all the necessaries libraries
    import plotly.offline as py
    import plotly.graph_objs as go
    import pandas as pd
    # In trace you specify what kind of plot you want (such scatter, bar, pie or so)
    trace = go.Scatter(
          x=[1,2,3,4,5,6,7,8,9],
          y=[1,2,3,4,5,6,7,8,9],
          name="trace1",
          mode="lines")
    # Data is just the list of your traces
    data = [trace]
    # Create layout if you want to add title to plot, to axis, choose position etc
    layout = go.Layout(
          title="My first plotly chart",
          xaxis=dict(title="X Values"),
          yaxis=dict(title="Y Values"))
    # Figure need to gather data and layout together
    fig = go.Figure(data=data, layout=layout)
    # This commandd plot the plot and create HTML file in your Python script directory
    py.iplot(fig, filename="first plot.html")
    

    2.Second way:

    # Import all the necessaries libraries
    import plotly.offline as py
    import plotly.graph_objs as go
    import pandas as pd
    # This code have the same result as previous, but it is more unreadable as I think
    fig = {
      "data": [
        {
          "x": [1,2,3,4],
          "y": [1,2,3,4],
          "name": "trace1",
          "type": "scatter"
        }],
      "layout": {
            "title":"My first plotly chart",
            "xaxis": {
                    "title": "X Values"
                    },
            "yaxis": {
                   "title": "Y Values"
                   }
                }
        }
    # Just plot
    py.iplot(fig, filename="first plot.html")
    

    If you want to customize your plot, I am suggest you to check plotly docs about scatter plot.

    Output: Output