I just discovered plotly and like it so far. I have this code provided by the main website
import plotly.plotly as py
from plotly.graph_objs import *
trace0 = Scatter(
x=[1,2,3,4],
y=[10,15,13,17]
)
trace1 = Scatter(
x=[1,2,3,4],
y=[16,5,11,9]
)
data = Data([trace0, trace1])
unique_url = py.plot(data, filename='basic-line')
I am curious about two things:
1) When I run this code, my browser automatically pops up and shows me the graph. All I want is the url so that I can later embed it in an html file. Is there a way to turn off the feature that opens my browser and shows me the graph?
2) Is there a way to get rid of the 'Play with this data' link?
I have combed through the documentation provided, but have come up empty-handed on these two issues.
To disable pop-ups you could use auto_open=FALSE and try the following
py.plot(data, filename='basic_line', auto_open=False)
py.plot(data, show_link=False) will take that link off (if you are referring to the link that says Export to plot.ly). At least it does using:
import plotly.offline as py. As for the link at the top (when you hover your mouse over the graph), I'm trying to get rid of the Save and edit plot in cloud but only find options for that under the java script version... and that hides the whole bar which has other useful items on it (javascript option is: {displayModeBar: false}). Obviously I am finding the reference to "play with this data" ambiguous. You can see the workaround I wrote here: Adding config modes to Plotly.Py offline - modebar
You can easily remove that Export to plot.ly link in the offline graph.
Open your saved html file in a text editor. and search for. {"showLink": true, "linkText": "Export to plot.ly"}
And change the true value to false.
Related
I am using Jupyter and Plotly to produce a set of plots, text and indicators that I then export in HTML, to produce a sort of "dashboard" that people can navigate to get data.
To produce an interactive table of contents, where users can click and go directly to the desired section, so far I followed this nice tutorial
https://sebastianraschka.com/Articles/2014_ipython_internal_links.html
The problem is that this only works with Markdown, and I would like to have instead something more adaptable and graphically pleasant.
I thought I could get away with producing a plotly multiplot with big clickable buttons to the different sections. Something like
--------------- --------------- ---------------
¦ Section 1 ¦ ¦ Section 2 ¦ ¦ Section 3 ¦
--------------- --------------- ---------------
So far, I'm able to get what I want using Markdowns. Internal link destinations in the notebook are defined as
from IPython.display import Markdown as md
#destination of an internal link
md(f"""<a id='Section_1'></a>""")
And they can be called as
md(f"""<a href='#Section_1'> Go to Section 1 </a>""")
Crucially, this also works when I export the notebook in html, which is the file I eventually send around.
However, when I try to put a link in a Plotly figure (via text annotation, for example) the situation is different. If I do something like that:
import plotly.graph_objects as go
import numpy as np
x = np.arange(10)
fig = go.Figure(data=go.Scatter(x=x, y=x**2))
fig.add_annotation(x=6, y=10,
text="<a href='#Section_1'>Go to Section 1</a>",
showarrow=False,
yshift=10)
fig.show()
two things can happen:
In the Jupyter notebook, if I click on the link, instead of jumping to the right session, it opens a new tab with a copy of the notebook, and then jumps to the session.
When I export it in html, the link is simply not transfered and - although clickable - nothing happens. Weirdly, if instead of referring to an internal section of the document I try an external link, say "www.wikipedia.com", it works just fine.
The code I use to export the notebook in html is
import plotly.offline as pyo
import plotly.io as pio
pyo.init_notebook_mode(connected=False)
pio.renderers.default = "notebook"
from nbconvert import HTMLExporter
from nbconvert import PDFExporter
from nbconvert.writers import FilesWriter
nb_name = 'My notebook'
exporter = HTMLExporter(exclude_input=True, exclude_output_prompt = True)
(body, resources) = exporter.from_filename(f'{nb_name}.ipynb')
write_file = FilesWriter()
write_file.write(
output=body,
resources=resources,
notebook_name=nb_name
)
Maybe the problem is how the link is exported in the html conversion, maybe it's with Plotly itself. Any idea or alternative I could use to get the result I want?
I created a plotly figure using python and I am aware that one can save the interactive figure in html format by using:
fig.write_html("name_of_figure.html")
For the axis labels, as well as the title of the figure, I used LaTeX fonts like this:
fig.update_layout(title=r'$\text{Some title}_2$')
When I render it in my browser directly the LaTeX fonts are displayed correctly. However, when I save the figure in .html format, the title, as well as the axis labels, are not rendered using LaTeX fonts. I rather see the plain text like $\text{Some title}_2$.
What can I do to circumvent that problem?
Add an include_mathjax = 'cdn' parameter to .write_html.
And read the documentation of write_html function carefully :)
include_mathjax: bool or string (default False)
Specifies how the MathJax.js library is included in the output html div string. MathJax is required in order to display labels with LaTeX typesetting.
If False, no script tag referencing MathJax.js will be included in the output.
If 'cdn', a script tag that references a MathJax CDN location will be included in the output. HTML div strings generated with this option will be able to display
LaTeX typesetting as long as internet access is available.
If a string that ends in '.js', a script tag is included that
references the specified path. This approach can be used to point the
resulting HTML div string to an alternative CDN.
import plotly.express as px
fig = px.line(x = [0,1,2], y = [0,1,4])
fig.update_layout(title=r'$\text{Some title}_2$')
fig.write_html("example_figure.html", include_mathjax = 'cdn')
I am creating a dashboard at the moment using Plotly express and Panel.
The charts when created with Plotly work fine, but once rendered into the dashboard they become buggy. When hovering over data points no hover information pops up, the plotly tools like zoom, pan and reset disappear and my mouse when moving around the chart turns into a double sided horizontal arrow that you would see when you hover over a scroll bar.
I will put enough code to recreate one of the charts in and outside of the dashboard so anyone who wants to can test and see if they get the same result.
# Getting BTC TWh csv straight from the download link so that whenever the notebook is ran, the data is the latest available
req = requests.get('https://static.dwcdn.net/data/cFnri.csv')
url_content = req.content
csv_file = open('Resources/btc_twh.csv', 'wb')
csv_file.write(url_content)
# Creating BTC TWh dataframe from csv
btc_twh_df = pd.read_csv(Path("Resources/btc_twh.csv"))
# Changing column names for readability and replacing '/' with '-' for plotting reasons
btc_twh_df.columns = ["date", "btc_estimated", "btc_minimum"]
btc_twh_df["date"] = btc_twh_df["date"].str.replace("/", "-")
btc_twh_df_subset.head()
# Plot ETH/BTC TWh with Plotly
btc_twh_chart = px.line(
btc_twh_df,
y="btc_estimated",
title="BTC Energy Usage",
color_discrete_map={"btc_estimated":"orange"},
labels={"btc_estimated":"BTC"})
btc_twh_chart.update_layout(xaxis_title="", yaxis_title="Energy Usage in TWh", template="plotly_dark", height=600, width=1000)
btc_twh_chart.show()
###################
# Plot chart within the dashboard
# TWh panes and column
twh_pane = pn.pane.Plotly(btc_twh_chart)
# Dashboard
dashboard = pn.Tabs(
("Welcome", twh_pane)
)
dashboard.servable()
See how that goes and let me know, it might be my 2017 Macbook Pro, although I haven't had processor issues so far, and my gut tells me it feels more like a bug.
If it works fine and you feel like investigating further here is my repo
https://github.com/kez4twez/mining_energy_usage
Feel free to clone it and try and run the whole dashboard.ipynb file and see what happens.
Thanks
I have to create a simple report that show one data table and have two logos in the top corners. The code below worked in a previous project but now that I’m reusing it on a new computer for a new project it wont show the logos.
I get no error message. Same version of plotly and python "plotly==4.6.0" "Python 3.6.1"
Please note that the only thing that changed is the data shown in the datatable.
import plotly.graph_objects as go
import pandas as pd
traces = go.Table(
header=dict(values=list(df.columns),
align='left'),
cells=dict(
values=df.T.values.tolist(),
align='left'))
layout = go.Layout(
title='Report <br> {}'.format( report_date),
title_x=0.5,
paper_bgcolor='#FFFFFF',
margin = {'t':100, 'b':40, 'r':40, 'l':40}
,images=[
dict(
source='assets\\MiniLogo.png',
xref='paper',yref='paper',
x=1,y=1.05,
sizex=0.2, sizey=0.2,
xanchor="right", yanchor="bottom"),
dict(
source='assets\\Titlelogo.png',
xref='paper',yref='paper',
x=0,y=1.05,
sizex=0.2, sizey=0.2,
xanchor="left", yanchor="bottom")
]
)
fig = go.Figure(
data=traces
,layout=layout)
fig.show()
I think the problem is within the source argument in your layout. I've used your code with this image URL instead of a relative path and it works perfectly and here is a screenshot knowing that I've used a simple table as my df:
In my opinion, you have two options to overcome that:
Upload these images to a cloud-service and use their URLs instead.
Or according to this Plolty community thread, you can use Pillow.Image class to read the image from your local machine. You can install it easily by running pip install pillow and modify your code to be like so:
from PIL import Image
layout= go.Layout(images= [dict(
source= Image.open('assets\\MiniLogo.png'),
...)])
I want to have multiple plotly plots on 1 html page without using the tools.make_subplots method. (I dont want to use that since I find that its not easy to read and I want a unique legend & layout in each of the subplot panels).
I want to define 2 figures with their own unique layouts, and arrange them arbitrarily on the page. I think I know how to do this with dash using the html.Div object, but I was wondering if there was an easy way to do this using only plotly?
I encountered the very same problem and followed the solution posted here:
Plotly: Plot multiple figures as subplots by Esostack
However, when I dumped the html of multiple figures into a single text file, I found the file size increasing by 5MB per figure that I add. 99.9% of this is caused by java script stuff that is added by plotly to make the plots interactive. Luckily, they also implemented a parameter to specify if you want to include the js or not. So you need to include it only for the first figure and skip it for the rest, like it is done in the following function. Hope that helps:
def figures_to_html(figs, filename):
'''Saves a list of plotly figures in an html file.
Parameters
----------
figs : list[plotly.graph_objects.Figure]
List of plotly figures to be saved.
filename : str
File name to save in.
'''
import plotly.offline as pyo
dashboard = open(filename, 'w')
dashboard.write("<html><head></head><body>" + "\n")
add_js = True
for fig in figs:
inner_html = pyo.plot(
fig, include_plotlyjs=add_js, output_type='div'
)
dashboard.write(inner_html)
add_js = False
dashboard.write("</body></html>" + "\n")
So, in conclusion, I have not found a way to do this purely with plotly. Below is my code for doing this with Dash, which has been working quite well:
Step 1: make a few plotly plots
import plotly.offline as pyo
import plotly.graph_objs as go
import plotly as py
fig1 = go.Scatter(y=[1,2,3])
fig2 = go.Scatter(y=[3,2,1])
plots = [fig1, fig2]
Step 2: Make dash Div objects:
app = dash.Dash()
layout = html.Div(
[html.Div(plots[i]) for i in range(len(plots))],
style = {'margin-right': '0px'}
)
Step 3: Run dash
app.layout = layout
app.run_server(port=8052)