running plotly.plotly.iplot() inside a funtion, no chart is shown - python

import plotly.plotly as py
import plotly.graph_objs as go
# Create random data with numpy
import numpy as np
N = 500
random_x = np.linspace(0, 1, N)
random_y = np.random.randn(N)
# Create a trace
trace = go.Scatter(
x = random_x,
y = random_y
)
def myplot(data):
print "ploting"
py.iplot(data, filename='basic-line')
data = [trace]
myplot(data)
#py.iplot(data, filename='basic-line')
As the code shown above, if I use function myplot, no chart is shown. But if I use py.iplot directly, the chart is shown. Any body can help?

just add this
py.init_notebook_mode(connected=True)

Related

capture user click in a variable from a plotly express sunburst chart

I am using the below code to generate a pie chart.
How does one capture name = "female" that appears when you click over a sector into a variable. ?
import plotly.express as px
df = px.data.tips()
fig = px.sunburst(df, path=['day', 'sex'], values='total_bill')
fig.show()
From what I have found so far there is a on_click callback. For testing when I do
a print statement, it does not show any thing. I need to open a explorer path based
on what user clicks. What's the possible way to do so ?
import plotly.graph_objects as go
import numpy as np
np.random.seed(1)
x = np.random.rand(100)
y = np.random.rand(100)
f = go.FigureWidget([go.Scatter(x=x, y=y, mode='markers')])
scatter = f.data[0]
# create our callback function
def update_point(trace, points, selector):
print(trace, points, selector)
subprocess.Popen(['explorer', 'path_build_after_user_clicks_on_a_sector'])
scatter.on_click(update_point)
f

Plotting multiple lines in plotly on the same graph using fig.show?

I have some old code that graphs lots of lines on the same graph in a manner like
import plotly.plotly as py
import plotly.graph_objs as go
data = [regtimes, avg5times]
py.iplot(data, filename='basic-line')
and this would graph both lines on the same plot. I tried to use this again and it says plotly.plotly is deprecated. Now I have something like
individualtimes = go.Scatter(
y = times,
x = x1,
)
test = go.Scatter(
y2=[1, 1, 5],
x2=x1
)
data = [individualtimes,test]
fig = go.Figure(data=data)
fig.show()
Is there a way to use fig.show to graph multiple lines like this? Thanks!
I have found the answer! It has been changes to use add_trace and then show the figure. Plotly uses
import plotly.graph_objects as go
# Create random data with numpy
import numpy as np
np.random.seed(1)
N = 100
random_x = np.linspace(0, 1, N)
random_y0 = np.random.randn(N) + 5
random_y1 = np.random.randn(N)
random_y2 = np.random.randn(N) - 5
# Create traces
fig = go.Figure()
fig.add_trace(go.Scatter(x=random_x, y=random_y0,
mode='lines',
name='lines'))
fig.add_trace(go.Scatter(x=random_x, y=random_y1,
mode='lines+markers',
name='lines+markers'))
fig.add_trace(go.Scatter(x=random_x, y=random_y2,
mode='markers', name='markers'))
fig.show()
The rest of this can be found here.

Plotly: How to set the range of the y axis?

I have the following code to create the line plot with Plotly. How can I set the range of Y axis to always have it in [0; 10]?
layout = go.Layout(
title=go.layout.Title(
text="Test",
xref='paper',
x=0
),
xaxis=go.layout.XAxis(
tickmode='linear',
tickfont=dict(
size=10
),
title=go.layout.xaxis.Title(
font=dict(
size=14,
color='#7f7f7f'
)
)
),
yaxis=go.layout.YAxis(
title=go.layout.yaxis.Title(
text=y,
font=dict(
size=14,
color='#7f7f7f'
)
)
)
)
data = [go.Scatter(x=x1, y=y1)]
Update for newer versions
When setting up a figure you can use plotly's magic underscore notation and specify layout_yaxis_range=[<from_value>, <to_value>] like this:
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-4,4])
Or if you've already got a figure named fig, you can use:
fig.update_layout(yaxis_range=[-4,4])
And:
fig.update(layout_yaxis_range = [-4,4])
Or:
fig.update_yaxes(range = [-4,4])
Figure:
Complete code:
# imports
import pandas as pd
import plotly.graph_objs as go
import numpy as np
# data
np.random.seed(4)
x = np.linspace(0, 1, 50)
y = np.cumsum(np.random.randn(50))
# plotly line chart
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-4,4])
fig.update_layout(yaxis_range=[-4,4])
fig.show()
Original answer using plotly.offline, iplot and no magic underscore notation:
When setting up a figure, use:
layout = go.Layout(yaxis=dict(range=[fromValue, toValue])
Or if you've already got a figure named fig, you can use:
fig.update_layout(yaxis=dict(range=[fromValue,toValue]))
Plot:
Complete code for Jupyter Notebook:
# imports
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import plotly.graph_objs as go
import numpy as np
# setup
init_notebook_mode(connected=True)
# data
np.random.seed(4)
x = np.linspace(0, 1, 50)
y = np.cumsum(np.random.randn(50))
# line
trace = go.Scatter(
x=x,
y=y,
)
# layout
layout = go.Layout(yaxis=dict(range=[-4,4])
)
# Plot
fig = go.Figure(data=[trace], layout=layout)
iplot(fig)
Some important details:
With this setup, you can easily add an y axis title like this:
# layout
layout = go.Layout(yaxis=dict(range=[-4,4]), title='y Axis')
)
It's a little more tricky if you'd like to format that title further. I find it easiest to actually add another element with title = go.layout.yaxis.Title(text='y Axis', font=dict(size=14, color='#7f7f7f'). As long as you do it the right way, you should not experience the situation in your comment above:
Thanks. I tried it. But then I have 2 definitions of yaxis in the
Layout: yaxis=dict(range=[0, 10]) and yaxis=go.layout.YAxis. Therefore
an error appears.
Take a look at this:
Plot:
Complete code with y-axis text formatting:
# imports
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import plotly.graph_objs as go
import numpy as np
# setup
init_notebook_mode(connected=True)
# data
np.random.seed(4)
x = np.linspace(0, 1, 50)
y = np.cumsum(np.random.randn(50))
# line
trace = go.Scatter(
x=x,
y=y,
)
# layout
layout = go.Layout(
yaxis=dict(range=[-4,4],
title = go.layout.yaxis.Title(text='y Axis', font=dict(size=14, color='#7f7f7f')))
)
# Plot
fig = go.Figure(data=[trace], layout=layout)
iplot(fig)
If I understand you right you want to limit the range of the y-axis itself. You can pass a dict in the keyword argument yaxis. It could be something like go.Layout(yaxis=dict(range=[0, 10])) I hope this helps you.

Plotly: Add line to bar chart

I have a plotly bar chart, from a dataframe:
fig = df.iplot(asFigure=True, kind='bar', barmode = 'relative')
py.iplot(fig)
Is it possible to turn one of the columns in the data frame into a line series?
The suggested link in the comments does have some valuable resources, but they won't answer your questions directly. iplot() uses a pandas dataframe as input, and produces a stacked barplot. Here's an approach that will let you do exactly that, albeit without using df.iplot()
First, the plot :
Now, the code
My suggestion builds on an example found at: plot.ly/pandas/bar-charts. As you'll see that's an example that builds on a pandas dataframe - just like df.iplot(). You can simply take a series or 'trace' out of the stacked bars and display it as a line by changing
go.Bar(x=df['x'],
y=df['y4'])
to:
go.Scatter(x=df['x'],
y=df['y4'])
I've also added a few elements to make it easier to display your results offline in a Jupyter notebook. Also note that I've changed the last line from py.iplot(fig, filename='pandas-bar-chart-layout') to just iplot(fig, filename='pandas-bar-chart-layout')
Complete snippet:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
import pandas as pd
import numpy as np
N = 20
x = np.linspace(1, 10, N)
y = np.random.randn(N)+3
y2 = np.random.randn(N)+6
y3 = np.random.randn(N)+9
y4 = np.random.randn(N)+12
df = pd.DataFrame({'x': x, 'y': y, 'y2':y2, 'y3':y3, 'y4':y4})
df.head()
data = [
go.Bar(
x=df['x'], # assign x as the dataframe column 'x'
y=df['y']
),
go.Bar(
x=df['x'],
y=df['y2']
),
go.Bar(
x=df['x'],
y=df['y3']
),
go.Scatter(
x=df['x'],
y=df['y4']
)
]
layout = go.Layout(
barmode='stack',
title='Stacked Bar with Pandas'
)
fig = go.Figure(data=data, layout=layout)
# IPython notebook
iplot(fig, filename='pandas-bar-chart-layout')
answering to the last comment, I changed the code to include a loop like you asked.
Let me know if this helps:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
import pandas as pd
import numpy as np
N = 20
x = np.linspace(1, 10, N)
y = np.random.randn(N)+3
y2 = np.random.randn(N)+6
y3 = np.random.randn(N)+9
y4 = np.random.randn(N)+12
df = pd.DataFrame({'x': x, 'y': y, 'y2':y2, 'y3':y3, 'y4':y4})
df.head()
data = []
for i in df.columns:
if i!= "x":
data.append(
go.Bar(
x=df['x'], # assign x as the dataframe column 'x'
y=df[i]
)
)
layout = go.Layout(
barmode='stack',
title='Stacked Bar with Pandas'
)
fig = go.Figure(data=data, layout=layout)
# IPython notebook
iplot(fig, filename='pandas-bar-chart-layout')

Setting legend text colour in Plotly 3.0

I have just installed the lastest Plotly (3.0) and I have not been able to set the legend text colour.
This is my code:
import plotly.graph_objs as go
import numpy as np
x = np.random.randn(1000)
y = np.random.randn(1000)
fig = go.FigureWidget({'x':x,'y':y,'type':'histogram2dcontour','colorscale':'Viridis'}],
layout=go.Layout(title='test',width=700,plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)'))
fig.layout.titlefont.color = 'orange'
fig.layout.xaxis.color = 'white'
fig.layout.yaxis.color = 'white'
fig.layout.legend.font.size = 2000
fig.layout.legend.font.color = 'red'
fig
As can be seen below the legend text below remains the same. Weirdly the attributes of fig.layout.legend.font.color include capitalise, isdigit class methods etc.
Is this a bug or am I missing something?
Any help much appreciated.
Thanks.
Because you are using histogram2contour the color-bar on the right is not a legend but actually an object called colorbar. To update it you can configure it's properties in your trace. I have an example below where I make the tick marks orange and the title red. I used Jupyter Notebooks to create the example so I had to configure it to offline but you don't have too. Here is the documentation for the color-bar object.
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
import numpy as np
x = np.random.uniform(-1, 1, size=500)
y = np.random.uniform(-1, 1, size=500)
trace = [go.Histogram2dContour(
x = x,
y = y,
colorbar=dict(
title='Colorbar',
tickfont={'color':'#E90' },
titlefont={"color":'#FF0000'}
),
)]
iplot(trace, filename = "Basic Histogram2dContour")

Categories