Display python plotly graph in RMarkdown html document - python

Why plotly package of python can not display figure in RMarkdown but matplotlib can? For example:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
```
```{r}
library(plotly)
subplot(
plot_ly(mpg, x = ~cty, y = ~hwy, name = 'default'),
plot_ly(mpg, x = ~cty, y = ~hwy) %>%
add_markers(alpha = 0.2, name = 'alpha'),
plot_ly(mpg, x = ~cty, y = ~hwy) %>%
add_markers(symbols = I(1), name = 'hollow')
)
```
```{python}
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
plotly.tools.set_credentials_file(username='xxx', api_key='xxx')
N = 500
trace0 = go.Scatter(x = np.random.randn(N), y = np.random.randn(N) + 2, name = "Above", mode = "markers",
marker = dict(size = 10, color = "rgba(152, 0, 0, .8)", line = dict(width = 2, color = "rgb(0,0,0)")))
trace1 = go.Scatter(x = np.random.randn(N), y = np.random.randn(N) - 2, name = "below", mode = "markers",
marker = dict(size = 10, color = "rgba(255, 182, 193, .9)", line = dict(width = 2, color = "rgb(0,0,0)")))
data = [trace0, trace1]
layout = dict(title = "Styled Scatter", yaxis = dict(zeroline = False), xaxis = dict(zeroline=False))
fig = dict(data = data, layout = layout)
py.iplot(fig, filename = "styled-scatter")
```
The R code can work well, but the python code can not dispay the figure, what is wrong with the code?

Here is what I did:
used plotly offline:
replace import plotly.plotly as py by import plotly.offline as py
no need to set username and api key in offline mode.
used py.plot(fig, filename = "styled-scatter.html", auto_open=False):
py.iplot() is for Jupyter notebooks (it embeds the plot directly into the Notebook)
auto_open = False argument is to avoid that the plot pops up.
embedded the html plot into the Rmarkdown by using the following:
```{r, echo=FALSE}
htmltools::includeHTML("styled-scatter.html")
```
and here is the result:

Related

how to add range to the secondary_y axis in plotly?

I want to create a graph where I want to add range to the secondary y-axis. The graph which I have right now is like this.
The code for this graph is like this:
import plotly.offline as pyo
import plotly.graph_objs as go
from plotly import tools
from plotly.subplots import make_subplots
import pandas as pd
import xlwings as xw
import logging
fileName = 'solar data.xlsx'
app = xw.App(visible=False)
try:
wb = app.books.open(fileName)
sheet = wb.sheets[4]
lastCell = sheet.range('A1').end('down').last_cell.row
solarOne = sheet.range('B2:B'+ str(lastCell)).value
bessOne = sheet.range('D2:D'+ str(lastCell)).value
socOne = sheet.range('E2:E'+ str(lastCell)).value
solarOne_Plus_bessOne = [i+j for i,j in zip(solarOne,bessOne)]
# solarTwo = sheet.range('F2:F' + str(lastCell)).value
# bessTwo = sheet.range('H2:H' + str(lastCell)).value
# socTwo = sheet.range('I2:I' + str(lastCell)).value
# solarTwo_Plus_bessTwo = [i + j for i, j in zip(solarTwo, bessTwo)]
except Exception as e:
logging.exception("Something awful happened!")
print(e)
finally:
app.quit()
app.kill()
fig = go.Figure()
projectTime = pd.date_range("2020-10-01 00:00:00", "2020-10-01 23:59:00", freq="1T")
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(go.Scatter(x = projectTime, y = solarOne, name = 'Solar', fill='tozeroy', line=dict(width=0.5, color='rgb(255,167,0)')), secondary_y=False)
fig.add_trace(go.Scatter(x = projectTime, y = bessOne, name = 'Storage', fill='tozeroy', line=dict(width=0.5, color='rgb(43, 201, 34)')), secondary_y=False)
fig.add_trace(go.Scatter(x = projectTime, y = socOne, name = 'SoC', fill='tozeroy', line=dict(width=0.5, color='rgb(250, 67, 67)')), secondary_y=True)
fig.add_trace(go.Scatter(x = projectTime, y = solarOne_Plus_bessOne, name = 'Solar + BESS', fill='tozeroy',), secondary_y=False)
# Add figure title
fig.update_layout(
title_text="Solar with 0.5MW 0.5Hour storage"
)
# Set x-axis title
fig.update_xaxes(title_text="Time")
# Set y-axes titles
fig.update_yaxes(title_text="Dispatch(MW) and SoC(MWh)")
pyo.plot(fig, filename='Solar with 0.5MW 0.5Hour storage example 1.html')
I have tried to add layout_yaxis_range=[-0.6, 0.7] in secondary y-axis but it throws an error
TypeError: add_trace() got an unexpected keyword argument 'layout_yaxis_range'
I want this secondary y-axis with the same x-axis. Can anyone please help?
This works for me in similar cases:
fig.update_yaxes(range=[-0.6, 0.7], secondary_y=True)

Bokeh how to get GlyphRenderer for Annotation

With Bokeh, how do I get a handle to the Renderer (or GlyphRenderer) for an Annotation? Is this possible?
I would like to be able to toggle a Band (which is an Annotation) on and off with an interactive legend, so I need to be able to pass a list of Renderers to the LegendItem constructor.
This code:
maxline = fig.line(x='Date', y=stn_max, line_width=0.5, legend=stn_max, name="{}_line".format(stn_max), color=stn_color, alpha=0.75, source=source)
minline = fig.line(x='Date', y=stn_min, line_width=0.5, legend=stn_min, name="{}_line".format(stn_min), color=stn_color, alpha=0.75, source=source)
band = bkm.Band(base='Date', lower=stn_min, upper=stn_max, fill_alpha=0.50, line_width=0.5, fill_color=stn_color, source=source)
bkm.LegendItem(label=stn, renderers=[maxline, minline, band])
Produces this error
...
ValueError: expected an element of List(Instance(GlyphRenderer)), got seq with invalid items [Band(id='1091', ...)]
For LegendItem only instances of GlyphRenderer can be passed to its renderers attribute and Band is not based on GlyphRenderer so it gives error. In the code below the Band visibility is being toggled by means of a callback:
from bokeh.plotting import figure, show
from bokeh.models import Band, ColumnDataSource, Legend, LegendItem, CustomJS
import pandas as pd
import numpy as np
x = np.random.random(2500) * 140 - 20
y = np.random.normal(size = 2500) * 2 + 5
df = pd.DataFrame(data = dict(x = x, y = y)).sort_values(by = "x")
sem = lambda x: x.std() / np.sqrt(x.size)
df2 = df.y.rolling(window = 100).agg({"y_mean": np.mean, "y_std": np.std, "y_sem": sem})
df2 = df2.fillna(method = 'bfill')
df = pd.concat([df, df2], axis = 1)
df['lower'] = df.y_mean - df.y_std
df['upper'] = df.y_mean + df.y_std
source = ColumnDataSource(df.reset_index())
p = figure(tools = "pan,wheel_zoom,box_zoom,reset,save")
scatter = p.scatter(x = 'x', y = 'y', line_color = None, fill_alpha = 0.3, size = 5, source = source)
band = Band(base = 'x', lower = 'lower', upper = 'upper', source = source)
p.add_layout(band)
p.title.text = "Rolling Standard Deviation"
p.xaxis.axis_label = 'X'
p.yaxis.axis_label = 'Y'
callback = CustomJS(args = dict(band = band), code = """
if (band.visible == false)
band.visible = true;
else
band.visible = false; """)
legend = Legend(items = [ LegendItem(label = "x", renderers = [scatter, band.source.selection_policy]) ])
legend.click_policy = 'hide'
scatter.js_on_change('visible', callback)
p.add_layout(legend)
show(p)
Result:

Plotly python scatterplot y axis not ordering

Plotly.py is having issues with the y axis. Data is not ordered. Even in the csv file the data is sorted in ascending order.
https://i.stack.imgur.com/SUOL3.png
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import math
#What is the filename
filename = 'output.csv'
#What is the X Value?
xvalue = 'total_students'
#What is the Y Value?
yvalue = 'realcount'
#What is the plot title?
PlotTitle = 'total_students'
filename = input("What is the filename? (WITH .CSV) ")
xvalue = input("What is the X value? ")
yvalue = input("What is the y Value? ")
PlotTitle = input("What is the title of this chart? ")
esc1 = pd.read_csv('output.csv', encoding='cp1252')
def random_color():
rgbl=[255,0,0]
random.shuffle(rgbl)
return tuple(rgbl)
esc1 = go.Scatter(
x = esc1[xvalue],
y = esc1[yvalue],
name = 'School',
mode = 'markers',
marker = dict(
size = 10,
sizemode='area',
sizeref=1,
color = 'rgba(66, 134, 244, .8)'
)
)
data = [esc1]
layout = dict(title = 'Total Student Scatter',
yaxis = dict(zeroline = True,
title=yvalue),
xaxis = dict(zeroline = True,
title=xvalue)
)
#fig = dict(data=data, layout=layout)
#py.iplot(fig, filename='styled-scatter')
plotly.offline.plot({
"data": data,
"layout": layout
},filename=PlotTitle+'.html', auto_open=False)
print("Finished")
Jeeze stack-overflow has a ton of quality control. I have to keep adding details so i hope this helps.
Hmm, also worked fine. My code:
#import all the necessary libraries
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import math
import random
#What is the filename
filename = 'output.csv'
#What is the X Value?
xvalue = 'total_students'
#What is the Y Value?
yvalue = 'realcount'
#What is the plot title?
PlotTitle = 'total_students'
filename = input("What is the filename? (WITH .CSV) ")
xvalue = input("What is the X value? ")
yvalue = input("What is the y Value? ")
PlotTitle = input("What is the title of this chart? ")
esc1 = pd.read_csv(filename)
#I don`t have your `output.csv` so I am created own DataFrame
#esc1 = pd.DataFrame({"total_students":["10","20","30","40","50"],\
# "realcount":["8","16","28","39","41"]})
def random_color():
rgbl=[255,0,0]
random.shuffle(rgbl)
return tuple(rgbl)
#That`s your scatter trace
trace = go.Scatter(
x = esc1[xvalue],
y = esc1[yvalue],
name = 'School',
mode = 'markers',
marker = dict(
size = 10,
sizemode='area',
sizeref=1,
color = 'rgba(66, 134, 244, .8)'
)
)
#Give trace to data
data = [trace]
#Create layout
layout = dict(title = 'Total Student Scatter',
yaxis = dict(zeroline = True,
title=yvalue),
xaxis = dict(zeroline = True,
title=xvalue)
)
fig = dict(data=data, layout=layout)
plotly.offline.plot(fig, filename=PlotTitle+'.html', auto_open=False)
print("Finished")
And plot looks nice (yaxis and xaxis order as expected):

Python - plotly hover icon not working

As far as I'm aware, I've copied the documentation exactly. I basically used the documentation code and tweaked it for my purposes. But when I run this bit of code, no hover feature with text appears on my plot.
#Initialize df
aviation_data = pd.DataFrame(columns=["Latitude","Longitude","Fatalities"])
aviation_data["Latitude"] = [40.53666,60.94444]
aviation_data["Longitude"] = [-81.955833,-159.620834]
aviation_data["Fatalities"] = [True,False]
#Initialize colorscale
scl = [[0,"rgb(216,15,15)"],[1,"rgb(5,10,172)"]]
#Initialize text data
text_df = "Fatal: " + aviation_data["Fatalities"].apply(lambda x: str(np.bool(x))) + '<br>' + \
"Latitude: " + aviation_data["Latitude"].apply(lambda x: str(x)) + '<br>' + \
"Longitude" + aviation_data["Longitude"].apply(lambda x: str(x))
#Initialize data
data = [ dict(
type = 'scattergeo',
locationmode = 'USA-states',
lon = aviation_data["Longitude"],
lat = aviation_data["Latitude"],
text = text_df,
mode = 'markers',
marker = dict(
size = 5,
opacity = 0.5,
reversescale=True,
autocolorscale=False,
symbol = 'circle',
line = dict(
width=1,
color='rgba(102, 102, 102)'
),
colorscale = scl,
cmin = 0,
color = aviation_data["Fatalities"].astype(int),
cmax = 1
))]
#Initialize layout
layout = dict(
title ='Aviation Incidents for the Years 2014-2016<br>\
(red indicates fatal incident, blue indicates non-fatal)',
geo = dict(
scope='usa',
projection=dict(type='albers usa'),
showland = True,
landcolor = "rgb(206, 206, 206)",
countrywidth = 0.5,
subunitwidth = 0.5
),
)
#Plot
fig = dict(data=data,layout=layout)
iplot(fig,validate=False)
Anyone know why my hover text isn't showing up?
In the last line of code you need to call this:
plotly.offline.plot(fig, validate=False)
Instead of:
iplot(fig, validate=False)
Also do not forget import plotly:
import plotly
Hope this will help

ipython plotly map render on a django template

This is what I am doing in an ipython notebook where the plotly graphs and everything gets generated without fail. After that I am taking the html form of the notebook and embedding it in a django template where everything is working other than the plotly graphs. I am not sure what needs to be done thats why I also tried installing plotly on npm and also including a reference to plotly.js through my template. Below are the codes.
import pandas as pd
import numpy as np
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *
init_notebook_mode()
data = pd.read_csv("storage/AviationDataUp.csv")
useful_columns = ['Event.Date', 'Location', 'Country', 'Latitude', 'Longitude', 'Purpose.of.Flight',\
'Total.Fatal.Injuries','Number.of.Engines','Air.Carrier']
data = data[useful_columns]
data = data[data['Country']=='United States']
accident_trace = Scattergeo(
locationmode = 'ISO-3',
lon = data['Longitude'],
lat = data['Latitude'],
mode = 'markers',
marker = dict(
size = 2,
opacity = 0.75,
color="rgb(0, 130, 250)"),
name = 'Accidents'
)
layout = dict(
title = 'Aviation Accidents in USA',
geo = dict(
scope = 'usa',
projection = dict(),
showland = True,
landcolor = 'rgb(250, 250, 250)',
subunitwidth = 1,
subunitcolor = 'rgb(217, 217, 217)',
countrywidth = 1,
countrycolor = 'rgb(217, 217, 217)',
showlakes = True,
lakecolor = 'rgb(255, 255, 255)'
) )
figure = dict(data=Data([accident_trace]), layout=layout)
iplot(figure)

Categories