K.I.N
K.I.N

Reputation: 129

Showing multiple chart by using Plotly

I try to show multiple charts on one figure by Plotly. Is there smart way to put several charts with 'for' or other way without creating each df object? What is the better way to show interactive map with many categories?

import random
import plotly.offline as py
py.init_notebook_mode(connected=True)
import plotly.graph_objs as go

N = 500
x = np.linspace(0, 1, N)
y = np.random.randn(N)

z = []
foo = ['apple','amazon','facebook',
       'google','ms','twitter','airbnb','tesla',
      'piedpiper','hooli']
for bar in range(0,N):
    z.append(random.choice(foo))

df = pd.DataFrame({'x': x, 'y': y, 'z':z})

# Hope to get feedback below
df_hooli = df.query("z=='hooli'")
df_pp = df.query("z=='piedpiper'")

data = [
    go.Scatter(
    x = df_hooli['x'], # assign x as the dataframe column 'x'
    y = df_hooli['y'],
    name = 'hooli'),

    go.Scatter(
    x = df_pp['x'], # assign x as the dataframe column 'x'
    y = df_pp['y'],
    name = 'piedpiper')

]

layout = go.Layout(
    title='scatter plot with pandas',
    yaxis=dict(title='random distribution'),
    xaxis=dict(title='linspace')
)

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

# IPython notebook
py.iplot(fig, filename='pandas/line-plot-title')

Upvotes: 0

Views: 396

Answers (1)

Serenity
Serenity

Reputation: 36645

Try to get query result and plot in cycle like here:

import random
import plotly.offline as py
py.init_notebook_mode(connected=True)
import plotly.graph_objs as go
import numpy as np
import pandas as pd

N = 500
x = np.linspace(0, 1, N)
y = np.random.randn(N)

z = []
foo = ['apple','amazon','facebook',
       'google','ms','twitter','airbnb','tesla',
      'piedpiper','hooli']
for bar in range(0,N): z.append(random.choice(foo))
df = pd.DataFrame({'x': x, 'y': y, 'z':z})

# get query result and plot it to data list
data = list()
for q in ["z=='hooli'","z=='piedpiper'"]:
    df2 = df.query(q)
    data.append(
       go.Scatter(
        x = df2['x'], # assign x as the dataframe column 'x'
        y = df2['y'],
        name = q.split('==')[1].replace("'",'')))

layout = go.Layout(
    title='scatter plot with pandas',
    yaxis=dict(title='random distribution'),
    xaxis=dict(title='linspace')
)

fig = go.Figure(data=data, layout=layout)
py.plot(fig)
py.iplot(fig, filename='line-plot-title')

Upvotes: 1

Related Questions