When rendering a plotly barplot with fig.show(), I get the plot exactly the way I developed it. But when I render it using streamlit's st.plotly_chart(), it gets with another appearance (without the bar labels).
This is how it should be (the plot I get when using fig.show()):
How it renders with st.plotly_chart() (dark theme):
And in light theme:
My code:
import pandas as pd
import streamlit as st
import plotly.express as px
df = pd.read_excel('file.xlsx', sheet_name='Current_Base')
fig = px.histogram(df,
x='number',
text_auto=True
)
fig.show()
st.plotly_chart(fig)
My relevant settings:
- os: macOS Monterey 12.1
- libs:
streamlit 1.3.1
plotly 5.5.0
Could anyone help me with this issue?
Related
This question already has answers here:
Plotly: How to display charts in Spyder?
(2 answers)
Closed 8 days ago.
The following code yields a graph.
import numpy as np, pandas as pd
import matplotlib.pyplot as plt
import plotly, plotly.express as px
arr = np.array(np.arange(stop=257, start=1).reshape(-1,4,4))
dfs = [pd.DataFrame(i, index=["row1", "row2", "row3", "row4"], columns=["col1", "col2", "col3", "col4"])for i in arr]
plt.plot(dfs[1])
plt.show()
but the following does not
import numpy as np, pandas as pd
import matplotlib.pyplot as plt
import plotly, plotly.express as px
arr = np.array(np.arange(stop=257, start=1).reshape(-1,4,4))
dfs = [pd.DataFrame(i, index=["row1", "row2", "row3", "row4"], columns=["col1", "col2", "col3", "col4"])for i in arr]
px.line(dfs[1],x=dfs[1].index, y="col1").show()
clarification: both codes show plots when run in terminal but I can only see plot from matplotlib when these codes are run in spyder (there spyder tab "plots" only contains plot from matplotlib).
That's because in your second code, you're calling plotly.express.line to make a plotly plot (which is interactive) and I don't think Spyder can handle that.
Plotly's Python graphing library makes interactive,
publication-quality graphs.
You have at least, three choices/workarounds:
Either (1) use Jupyter Notebook or Jupyterlab.
Or (2) in Spyder, make the plot static (as well as your matplotlib plot) by adding these two lines :
import plotly.io as pio
pio.renderers.default='svg'
Or (3), always in Spyder, set your default Internet browser as the renderer :
import plotly.io as pio
pio.renderers.default='browser'
I have tried following the docs and various posts that discuss this and I have gotten nowhere. I am rendering the choropleth counties map from the plotly example, but I can't seem to figure out how to hide the colorbar. This is what I have tried:
import plotly.express as px
from urllib.request import urlopen
import json
import pandas as pd
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
fig = px.choropleth(
df,
geojson=counties,
locations='fips',
color='unemp',
color_continuous_scale="Viridis",
range_color=(0, 12),
scope="usa",
labels={'unemp':'Unemployment'}
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}, coloraxis=dict(showscale=False))
fig.update(layout_coloraxis_showscale=False)
fig.update_traces(showlegend=False)
fig.update(layout_showlegend=False)
fig.update_traces(showscale=False)
fig.show()
My result is always the same:
I suggest you check your plotly version using
import plotly
plotly.__version__
If it is less than 5.1.0 then I suggest you update it using the following pip command
pip install -Iv plotly==5.1.0
I just used your code only and with this specific version of plotly i am getting a map without the colorbar
I have a dataframe named "Actuals", indexed by time. This is how I want to plot the Load column.
fig = go.Figure([go.Scatter(x=Actuals.index, y= Actuals['Load (kW)'])])
fig.show()
When I run this part, it executes without rising any error. but it doesn't display the figure. What is the issue and how can I resolve it?
I am using Google colaboratory
I should have added this line of code:
import plotly.io as pio
pio.renderers.default = 'colab'
I searched whole day how to display the outputs of plotly plots in google colaboratory jupyter notebooks. There is a stackoverflow question and also official tutorial from google colaboratory but both of them did not work for me.
official link:
https://colab.research.google.com/notebooks/charts.ipynb#scrollTo=hFCg8XrdO4xj
stackoverflow question:
Plotly notebook mode with google colaboratory
https://colab.research.google.com/drive/14oudHx5e5r7hm1QcbZ24FVHXgVPD0k8f#scrollTo=8RCjUVpi2_xd
The built-in google colaboratory plotly version is 1.12.12.
Test plotly version
import plotly
plotly.__version__
1.12.12
Load libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
Mount google drive
from google.colab import drive
drive.mount('/content/drive')
dat_dir = 'drive/My Drive/Colab Notebooks/data/'
Official google colaboratory method (FAILED)
# https://colab.research.google.com/notebooks/charts.ipynb#scrollTo=hFCg8XrdO4xj
def enable_plotly_in_cell():
import IPython
from plotly.offline import init_notebook_mode
display(IPython.core.display.HTML('''
<script src="/static/components/requirejs/require.js"></script>
'''))
init_notebook_mode(connected=False)
Test official suggestion (FAILED)
import plotly.plotly as py
import numpy as np
from plotly.offline import iplot
from plotly.graph_objs import Contours, Histogram2dContour, Marker, Scatter
enable_plotly_in_cell()
x = np.random.randn(2000)
y = np.random.randn(2000)
iplot([Histogram2dContour(x=x, y=y, contours=Contours(coloring='heatmap')),
Scatter(x=x, y=y, mode='markers', marker=Marker(color='white', size=3, opacity=0.3))], show_link=False)
Stackoverflow Bob Smith Method
# https://stackoverflow.com/questions/47230817/plotly-notebook-mode-with-google-colaboratory
def configure_plotly_browser_state():
import IPython
display(IPython.core.display.HTML('''
<script src="/static/components/requirejs/require.js"></script>
<script>
requirejs.config({
paths: {
base: '/static/base',
plotly: 'https://cdn.plot.ly/plotly-1.5.1.min.js?noext',
},
});
</script>
'''))
Test Bob Smith method (FAILED)
# https://colab.research.google.com/drive/14oudHx5e5r7hm1QcbZ24FVHXgVPD0k8f#scrollTo=8RCjUVpi2_xd
import plotly.plotly as py
import numpy as np
from plotly.offline import init_notebook_mode, iplot
from plotly.graph_objs import Contours, Histogram2dContour, Marker, Scatter
configure_plotly_browser_state()
init_notebook_mode(connected=False)
x = np.random.randn(2000)
y = np.random.randn(2000)
iplot([Histogram2dContour(x=x, y=y, contours=Contours(coloring='heatmap')),
Scatter(x=x, y=y, mode='markers', marker=Marker(color='white', size=3, opacity=0.3))], show_link=False)
Questions
How to display the plotly output in google colaboratory?
Is is possible ? If so which version of plotly or cufflinks is working for you?
If it is not possible to display, can we save the output file as .html in our google drive and open them manually and see them?
I appreciate your help.
plotly version 4.x
As of version 4, plotly renderers know about Colab, so the following is sufficient to display a figure in both Colab and Jupyter (and other notebooks like Kaggle, Azure, nteract):
import plotly.graph_objects as go
fig = go.Figure( go.Scatter(x=[1,2,3], y=[1,3,2] ) )
fig.show()
plotly version 3.x
I was also struggling to display the plotly graphs in Google colab and stumbled upon this thread where you explained the problems with different solutions over the net. Feelings are the same for each one of the solutions. Finally, my search ended when I came across this video.
I followed his approach (might be similar to the ones you already tried) and this worked for me.
Upgrade plotly in colab thru !pip install plotly --upgrade and restart runtime as suggested.
Comment the upgrade option before re-running your notebook
Define the function configure_plotly_browser_state()
Invoke plotly libraries
Call function and notebook mode like below in every cell where you want to call iplot
configure_plotly_browser_state()
init_notebook_mode(connected=False)
iplot(XXXXXX)
Just import plotly libraries
Please let me know if this helps :)
Try to use renderer="colab" as shown below:
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Bar(y=[2, 1, 3])],
layout_title_text="A Figure Displayed with the 'colab' Renderer"
)
fig.show(renderer="colab")
Add line '%matplotlib inline' at the beginning of notebooks
Refer below link:
https://github.com/jupyter/notebook/issues/3523
use
import plotly.io as pio
pio.renderers.default = "colab"
it works for me on plotly version 5.5.0
Use plot and not iplot ...it took me a while for this one to figure out. You can the plot both to the notebook and to gdrive.
In my jupyter notebook, I made an offline interactive plot with plotly. I'm trying to save this interactive plot as a html file locally.
Below is my code. However, I cannot find my file I intended to save anywhere. Does anyone know what I did wrong?
Thanks a lot.
py.offline.init_notebook_mode(connected=True)
import plotly as py
import plotly.graph_objs as go
import numpy as np
y = np.random.randn(500)
data = [go.Histogram(y=y)]
py.offline.iplot(data, filename='myplot.html')
You're using iplot which is the interactive plot method that plots it in the Jupyter notebook for you to see. If you want to generate the HTML file change iplot to plot and it will create it for you:
import plotly as py
py.offline.init_notebook_mode(connected=True)
import plotly.graph_objs as go
import numpy as np
y = np.random.randn(500)
data = [go.Histogram(y=y)]
py.offline.plot(data, filename='myplot.html')
Plotly 4.x:
Use to_html or write_html.
import plotly.io as pio
import plotly.express as px
df = px.data.iris()
fig = px.bar(df, x='sepal_length', y='sepal_width')
pio.write_html(fig, file='iris.html')
reference
Moreover, if you are using Cufflinks or any other offline mode, you can export the html interactive graph in the following way:
# Original cufflinks call to plot the graph within a Jupyter Notebook:
plyo.iplot(pv.iplot(asFigure=True,kind='bar',xTitle='REF',yTitle='Defects',title='Kind of Defects',barmode='stack'))
# Export to html file
fig =pv.iplot(asFigure=True,kind='bar',xTitle='REF',yTitle='Defects',title='Kind of Defects',barmode='stack')
pio.write_html(fig, file='defects.html')