Python - Plotly - sample code error (iplot) - python

Hello everyone,
My purpose is to run the below plotly sample code and save the output as HTML file on my hard drive.
Any idea for a go around?
When I run the code I get the following error:
File "C:\Users\rbiberma\AppData\Local\Continuum\anaconda3\lib\site-packages\chart_studio\api\v2\utils.py", line 179, in request
raise exceptions.PlotlyRequestError(message, status_code, content)
PlotlyRequestError: No message
The error is triggered by the code line: py.iplot(fig1, filename='table-right-aligned-plots')
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
import pandas as pd
table_trace1 = go.Table(
domain=dict(x=[0, 0.5],
y=[0, 1.0]),
columnwidth = [30] + [33, 35, 33],
columnorder=[0, 1, 2, 3, 4],
header = dict(height = 50,
values = [['<b>Date</b>'],['<b>Number<br>transactions</b>'],
['<b>Output<br>volume(BTC)</b>'], ['<b>Market<br>Price</b>']],
line = dict(color='rgb(50, 50, 50)'),
align = ['left'] * 5,
font = dict(color=['rgb(45, 45, 45)'] * 5, size=14),
fill = dict(color='#d562be')),
cells = dict(values = [df[k].tolist() for k in
['Date', 'Number-transactions', 'Output-volume(BTC)', 'Market-price']],
line = dict(color='#506784'),
align = ['left'] * 5,
font = dict(color=['rgb(40, 40, 40)'] * 5, size=12),
format = [None] + [", .2f"] * 2 + [',.4f'],
prefix = [None] * 2 + ['$', u'\u20BF'],
suffix=[None] * 4,
height = 27,
fill = dict(color=['rgb(235, 193, 238)', 'rgba(228, 222, 249, 0.65)']))
)
trace1=go.Scatter(
x=df['Date'],
y=df['Hash-rate'],
xaxis='x1',
yaxis='y1',
mode='lines',
line=dict(width=2, color='#9748a1'),
name='hash-rate-TH/s'
)
trace2=go.Scatter(
x=df['Date'],
y=df['Mining-revenue-USD'],
xaxis='x2',
yaxis='y2',
mode='lines',
line=dict(width=2, color='#b04553'),
name='mining revenue'
)
trace3=go.Scatter(
x=df['Date'],
y=df['Transaction-fees-BTC'],
xaxis='x3',
yaxis='y3',
mode='lines',
line=dict(width=2, color='#af7bbd'),
name='transact-fee'
)
axis=dict(
showline=True,
zeroline=False,
showgrid=True,
mirror=True,
ticklen=4,
gridcolor='#ffffff',
tickfont=dict(size=10)
)
layout1 = dict(
width=950,
height=800,
autosize=False,
title='Bitcoin mining stats for 180 days',
margin = dict(t=100),
showlegend=False,
xaxis1=dict(axis, **dict(domain=[0.55, 1], anchor='y1', showticklabels=False)),
xaxis2=dict(axis, **dict(domain=[0.55, 1], anchor='y2', showticklabels=False)),
xaxis3=dict(axis, **dict(domain=[0.55, 1], anchor='y3')),
yaxis1=dict(axis, **dict(domain=[0.66, 1.0], anchor='x1', hoverformat='.2f')),
yaxis2=dict(axis, **dict(domain=[0.3 + 0.03, 0.63], anchor='x2', tickprefix='$', hoverformat='.2f')),
yaxis3=dict(axis, **dict(domain=[0.0, 0.3], anchor='x3', tickprefix=u'\u20BF', hoverformat='.2f')),
plot_bgcolor='rgba(228, 222, 249, 0.65)'
)
fig1 = dict(data=[table_trace1, trace1, trace2, trace3], layout=layout1)
plotly.offline.plot(fig1, filename="table-right-aligned-plots")
The desired output:
Answer:
py.iplot(fig1, filename='table-right-aligned-plots')
Should be replaced with: plotly.offline.plot(fig1, filename="table-right-aligned-plots")

I don't think there is currently a way to take what isn't HTML and make it such. Plotly's documentation doesn't list it as an option. You could export the static image in any of a number of ways (you'll note png, webp, jpeg and are built-in, amongst other options). You could also look at kaleido to see if that does what approximately what you need.
But perhaps what you really need is a different graphing library like Plotly's Dash.

Related

Hiding Duplicate Legend in Plotly

I'm new in using plotly and I'm trying to make a 2 different graph and show them individually through button; however, when I make it, the legends duplicated, resulting to a bad visualization of the data. Here's the code that I'm running right now:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import plotly as ply
import plotly.express as px
import plotly.graph_objects as go
url = "https://raw.githubusercontent.com/m23chaffee/DS100-Repository/main/Aluminum%20Alloy%20Data%20Set.csv"
alloy = pd.read_csv('https://raw.githubusercontent.com/m23chaffee/DS100-Repository/main/Aluminum%20Alloy%20Data%20Set.csv')
del alloy['temper']
alloy = alloy.rename(columns={'aluminum_alloy':'Alloy Number',
'modulus_elastic': 'Elastic Modulus',
'modulus_shear': 'Shear Modulus',
'strength_yield': 'Yield Strength',
'strength_tensile': 'Tensile Strength'
})
bar1 = px.bar(alloy,
x = "Alloy Number",
y = ["Elastic Modulus", "Shear Modulus","Yield Strength","Tensile Strength"],
barmode = 'group',
width = 1100,
height =500,
orientation = 'v',
color_discrete_sequence = px.colors.qualitative.Pastel,
labels={"value": "Data Values"},
template = 'seaborn').update_traces(legendgroup="group").update_layout(showlegend=False)
line1 = px.line(alloy,
x = "Alloy Number",
y = ["Elastic Modulus", "Shear Modulus","Yield Strength","Tensile Strength"],
width = 1100,
height =500,
orientation = 'v',
color_discrete_sequence = px.colors.qualitative.Pastel,
labels={"value": "Data Values"},
template = 'seaborn').update_traces(legendgroup="group", visible = 'legendonly').update_layout(showlegend=False)
# Add buttom
fig.update_layout(
updatemenus=[
dict(
type = "buttons",
direction = "left",
buttons=list([
dict(
args=['type', 'bar'],
label="Bar Graph",
method="restyle",
),
dict(
args=["type", "line"],
label="Line Graph",
method="restyle"
)
]),
pad={"r": 10, "t": 10},
showactive=True,
x=0.11,
xanchor="left",
y=1.1,
yanchor="middle"
),
]
)
fig.show()
and the result of the image would look like this:
Result of the code above
Attempted Solution
I tried to hide it using traces and in the documentation but it seems it didn't work out for me. I also found a similar stackoverflow post 8 years ago, tried it, and it didn't make any changes in my graph.

Plotly Express: Writing image not working, processes for several minutes until Keyboard Interrupted

Attempting to save a figure to my computer, and no matter what I try, it just does not work! Here's what I'm exactly trying to save, and the code block just continues to "run" until I Keyboard Interrupt.
import plotly.express as px
import plotly.io as pio
pio.renderers.default = 'notebook_connected'
fig = px.box(df, y = 'Total Series', x = 'Periods', color = 'Periods', color_discrete_sequence=['grey', 'purple', 'red'])
fig.update_layout(showlegend = False,
paper_bgcolor="white",
plot_bgcolor='rgba(0,0,0,0)',
width = 800,
title = {'text': 'Title',
'x': 0.5,
'xanchor': 'center',
'yanchor': 'top'},
title_font = {'family': 'Verdana',
'color': 'rgb(0, 82, 136)'})
fig.update_xaxes({'title': "",
'color': 'rgb(0, 82, 136)'})
fig.update_yaxes({'title': "",
'color': 'rgb(0, 82, 136)'})
fig.update_traces(opacity=0.70)
fig.write_image('boxplot_generated/image.png')
When I attempt to use an extremely simple example, the same thing happens. What am I doing wrong? Where could the problem be coming from? I pip installed orca and kaleido and even imported them in the Jupyter notebook (VSCode). Here's the simplified example I tried.
df = pd.DataFrame({'A': [1, 3, 5, 6], 'B': [1, 2, 7, 8 ]})
fig = px.line(df, x = 'A')
fig.write_image('image.png')
I know it's kind of difficult to replicate because it's gotta be something outside of the code, but any help would be appreciated.
try:
pio.write_image(fig, 'boxplot_generated/image.png')

Problem with visualization with Python Plotly Pandas?

I have Pandas data frame like this: data = pd.DataFrame({"Risk":["good", "bad", "good", "good", "bad"], "Age":[22, 50, 43, 27, 19]})
and I wan to achieve something like this:
Why my code does not work ? Could you repare my code? I have error that: AttributeError: 'list' object has no attribute 'loc'
import plotly.graph_objects as go
import plotly.tools as tls
import chart_studio.plotly as py
df_good = data.loc[data["Risk"] == 'good']['Age'].values.tolist()
df_bad = data.loc[data["Risk"] == 'bad']['Age'].values.tolist()
df_age = data['Age'].values.tolist()
#First plot
trace0 = go.Histogram(
x=df_good,
histnorm='probability',
name="Good Credit"
)
#Second plot
trace1 = go.Histogram(
x=df_bad,
histnorm='probability',
name="Bad Credit"
)
#Third plot
trace2 = go.Histogram(
x=df_age,
histnorm='probability',
name="Overall Age"
)
#Creating the grid
fig = tls.make_subplots(rows=2, cols=2, specs=[[{}, {}], [{'colspan': 2}, None]],
subplot_titles=('Good','Bad', 'General Distribuition'))
#setting the figs
fig.append_trace(trace0, 1, 1)
fig.append_trace(trace1, 1, 2)
fig.append_trace(trace2, 2, 1)
fig['layout'].update(showlegend=True, title='Age Distribuition', bargap=0.05)
py.iplot(fig, filename='custom-sized-subplot-with-subplot-titles')

Dynamically adding traces to graph with dropdown input

I'm currently working on my first web-application. I recently started following tutorials on python and on some modules. Most of the questions I have I'm able to figure by looking them up, exceptfor this one. I can't figured it out.
Goal is as follows:
- I'm trying to show a graph with a line-chart which dynamically updates by the user input. The user can choose multiple items from a multiple value dropdown.
If I add multiple 'go.Scatters' I can add multiple lines to the graph, except then the trace in the graph is static. So, I tried to write a for loop in go.Scatter that adds more go.Scatters for each item in data_name. Each time I try I got syntax erros. I tried to add values to the data list in dcc.Graph. Each time i failed.
The questions I've are the following:
- Where can i add the for loop to add traces to the data list?
- How should the for loop be structed?
I'm just a beginner so every advice is welcome :-)
Thanks in advance.
If i'm not clear enough on the question, please let me know.
My code is the following:
import dash
import dash_core_components as dcc
import dash_html_components as html
from pandas_datareader.data import DataReader
import time
from collections import deque
import plotly.graph_objs as go
import random
app = dash.Dash('vehicle-data')
max_length = 50
#times = deque(maxlen=max_length)
times = [1,2,3,4,5,6,7,8,9,10,11,12]
oil_temps = [11,12,13,14,15,16,17,18,19]
intake_temps = [11,12,13,14,15,16,17,18,19]
coolant_temps = [11,12,13,14,15,16,17,18,19]
#rpms = deque(maxlen=max_length)
#speeds = deque(maxlen=max_length)
#throttle_pos = deque(maxlen=max_length)
data_dict = {"NH Utrecht":oil_temps,
"NH Amsterdam": intake_temps,
"NH Schiller": coolant_temps
#"NH Sparrenhorst":rpms,
#"Amsterdam":speeds,
#"Overig":throttle_pos
}
app.layout = html.Div([
html.Div([
html.H2('Hotel',
style={'float': 'left',
}),
]),
dcc.Dropdown(id='vehicle-data-name',
options=[{'label': s, 'value': s}
for s in data_dict.keys()],
value=['NH Utrecht'],
multi=True
),
html.Div(children=html.Div(id='graphs'), className='row'),
dcc.Interval(
id='graph-update',
interval=100),
], className="container",style={'width':'98%','margin-left':10,'margin-right':10,'max-width':50000})
#app.callback(
dash.dependencies.Output('graphs','children'),
[dash.dependencies.Input('vehicle-data-name', 'value')],
events=[dash.dependencies.Event('graph-update', 'interval')]
)
def update_graph(data_names):
graphs = []
#update_obd_values(times, oil_temps, intake_temps, coolant_temps, rpms, speeds, throttle_pos)
if len(data_names)>2:
class_choice = 'col s12 m6 l4'
elif len(data_names) == 2:
class_choice = 'col s12 m6 l6'
else:
class_choice = 'col s12'
html.Div(children=
graphs.append(dcc.Graph(
figure=go.Figure(
data = [
go.Scatter(
x=times,
y=[16, 13, 10, 11, 28, 37, 43, 55, 56, 88, 105, 156],
name='Hotel Okura',
marker=go.Marker(
color='rgb(55, 83, 109)'
),
type='scatter',
connectgaps=True
),
],
layout=go.Layout(
title='Hotel comparison data',
showlegend=True,
legend=go.Legend(
x=1.0,
y=1.0
),
margin=go.Margin(l=40, r=0, t=40, b=30)
),
),
style={'height': 300},
id='my-graph'
)
))
return graphs
external_css = ["https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"]
for css in external_css:
app.css.append_css({"external_url": css})
external_js = ['https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js']
for js in external_css:
app.scripts.append_script({'external_url': js})
if __name__ == '__main__':
app.run_server(debug=True)
The for loop I used is the following (which obviously doesn't work because i try to add a graph in stead of a data time. But data.append doesn't work):
for data_name in data_names:
graph.append(go.Scatter(
x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
name='Voorbeeld',
marker=go.Marker(
color='rgb(255, 153, 0)'
),
type='scatter'
))

python-plotly-boxplot Why not showing the max and minimum value on graph

This is my data:[0, 45, 47, 46, 47,47,43,100].
And picture looks like this:
https://plot.ly/~zfrancica/8/
I want to have a picture like this: https://plot.ly/~zfrancica/9/
(an out come picture of [0, 45, 47, 46, 100] )
I want to have a fixed 0 minimum and 100 maximum.(May be this is not the correct box plot but I want to fix the minimum and maximum.) How should I do this?
(If ploty can't do this, a matplotlib plot code would also be fine.)
My code:
import plotly.plotly as py
import plotly.graph_objs as go
def box_plot(**kwargs):
print kwargs
num = len(kwargs['circum'])
#WornPercentage = go.Box(x=kwargs['circum'])
#data = [WornPercentage]
#py.iplot(data)
data = [
go.Box(
x=kwargs['circum'],
boxpoints='all',
jitter=0.3,
pointpos=-1.8
)
]
py.iplot(data)
process_dict={'circum':[0, 45, 47, 46, 47,47,43,100]}
box_plot(**process_dict)
Credentials
For those who don't know how to save credentials permanently;
import plotly.tools as tls
tls.set_credentials_file(username='username', api_key='api-key')
Assuming you have already saved your credentials;
A - Simple Solution
For a single one dimensional data;
import plotly.plotly as py
import plotly.graph_objs as go
trace0 = go.Box(
y=[0, 45, 47, 46, 47, 47, 43, 100], # Data provided
name = 'Provided Data Chart',
marker = dict(
color = 'rgb(0, 0, 255)' # Blue : #0000FF
)
)
data = [trace0]
py.plot(data) # Using plot instead of iplot
A - Output
B - Using Layout
And you can also check this out for a nicer layout, there is a range option you can use, for when autorange is set to False;
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.graph_objs import Layout
from plotly.graph_objs import Font
from plotly.graph_objs import YAxis
from plotly.graph_objs import Figure
trace0 = go.Box(
y=[0, 45, 47, 46, 47, 47, 43, 100], # Data provided
name = 'Provided Data Chart',
marker = dict(
color = 'rgb(0, 0, 255)' # Blue : #00FF00
)
)
data = [trace0]
layout = Layout(
autosize=True,
font=Font(
family='"Droid Sans", sans-serif'
),
height=638,
title='Plotly Box Demo',
width=1002,
yaxis=YAxis(
autorange=False, # Autorange set to False
range=[0, 100], # Custom Range
title='Y units', # To be changed, units
type='linear' # Use 'log' for appropriate data
)
)
fig = Figure(data=data, layout=layout)
plot_url = py.plot(fig) # Using plot instead of iplot
B - Output
Hope that it helps.

Categories