The graph is not showing up in my jupyter notebook in kaggle - python

I am not able to see my plot in my kaggle notebook.
The following is my code.
import ipywidgets as widgets
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
import seaborn as sns
df = pd.read_csv('../input/sdd1247/COMED_hourly.csv', parse_dates=["Datetime"], index_col="Datetime")
def Visualization_plots(x):
y = df.loc['2017']
y['COMED_MW'].resample('H').mean().plot()
button = widgets.Button(
description='Submit',
disabled=False,
button_style='success', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Click me',
icon='alicorn' # (FontAwesome names without the `fa-` prefix)
)
button.on_click(Visualization_plots)
button
The button shows up.. but when I click on it, I expected the graph to show below it. But nothing shows up.
I do however see the graph in the console. How can I show the graph in my notebook instead?
This is how it shows up in the console window:

I would add plt.show() on the line after the plot instruction.
If it doesn't work please provide a few lines of your dataset.

Related

how to create an QuantFig using cufflinks with iplot in jupyter notebook

import ipywidgets as wd
import cufflinks as cf
import pandas as pd
import yfinance as yf
from plotly.offline import iplot,init_notebook_mode
from ipywidgets import interact,interact_manual
init_notebook_mode()
stocks=['QQQ','MSFT','GOOGL','FB','TSLA','AAPL']
indicators=['Bollinger Bands','MACD','RSI']
def ta_dashboard(asset,indicator,start_date,end_date,bb_k,bb_n,macd_fast,macd_slow,macd_signal,rsi_periods,rsi_upper,rsi_lower):
df=yf.download(asset,start=start_date,end=end_date,progress=False,auto_adjust=True)
qf=cf.QuantFig(df,title=f'TA Dashboard={asset}',legend='right',name=f'{asset}')
if 'Bollinger Bands' in indicator:
qf.add_bollinger_bands(periods=bb_n,boll_std=bb_k)
if 'MACD' in indicator:
qf.add_macd(fast_period=macd_fast,slow_period=macd_slow,signal_period=macd_signal)
if 'RSI' in indicator:
qf.add_rsi(period=rsi_periods,rsi_upper=rsi_upper,rsi_lower=rsi_lower,showbands=True)
return qf.iplot()
controls_dict={'asset':stocks_selector,
'indicator':indicator_selector,
'start_date':start_date_selector,
'end_date':end_date_selector,
'bb_k':k_param,
'bb_n':n_param,
'macd_fast':macd_fast,
'macd_slow':macd_slow,
'macd_signal':macd_signal,
'rsi_periods':rsi_period,
'rsi_upper':rsi_upper,
'rsi_lower':rsi_lower}
ui=wd.HBox([main_selector_box,secondary_selector_box])
out=wd.interactive_output(ta_dashboard,controls_dict)
I got the error message:
PlotlyRequestError: Authentication credentials were not provided which point to return qf.plot() part
I saw some post on stackoverflow says change iplot() to fig.show()
I want to change it to qf.show() but got another error qf don't have show()
what can I do now?
I notice this in recent github issue in cufflink respository.
Add cf.go_offline() help to solve the problem because now it have offline mode and online mode
I change it to
def ta_dashboard(asset,indicator,start_date,end_date,bb_k,bb_n,macd_fast,macd_slow,macd_signal,rsi_periods,rsi_upper,rsi_lower):
cf.go_offline()
df=yf.download(asset,start=start_date,end=end_date,progress=False,auto_adjust=True)
qf=cf.QuantFig(df,title=f'TA Dashboard={asset}',legend='right',name=f'{asset}')
if 'Bollinger Bands' in indicator:
qf.add_bollinger_bands(periods=bb_n,boll_std=bb_k)
if 'MACD' in indicator:
qf.add_macd(fast_period=macd_fast,slow_period=macd_slow,signal_period=macd_signal)
if 'RSI' in indicator:
qf.add_rsi(period=rsi_periods,rsi_upper=rsi_upper,rsi_lower=rsi_lower,showbands=True)
return qf.iplot()
and it works
From Cufflinks github issue: https://github.com/santosjorge/cufflinks/issues/267

interactive plot geopandas doesn't show

I have this code from this website:
https://geopandas.org/en/stable/docs/user_guide/interactive_mapping.html
import geopandas as gpd
import matplotlib.pyplot as plt
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
world.explore(column='pop_est',cmap='Set2')
plt.show()
I try to run the code, the geodataframe data is printed but no plot is shown.
What am i missing?
Thnx in advanced.
world.explore(column='pop_est',cmap='Set2') should return and display a folium map object so you shouldn't need that plt.show() as the bottom.
Also, since you're using an IDE (not jupyter) we need to write the map to disk then open it up in the broswer.
Try
import geopandas as gpd
import webbrowser
import os
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
# world.explore() returns a folium map
m = world.explore(column='pop_est',cmap='Set2')
# and then we write the map to disk
m.save('my_map.html')
# then open it
webbrowser.open('file://' + os.path.realpath('my_map.html'))
export() creates a folium object, not a matplotlib figure
in jupyter just have m as last item in code cell
in other environments you can save as HTML and launch into a browser
import geopandas as gpd
import webbrowser
from pathlib import Path
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
m = world.explore(column='pop_est',cmap='Set2')
f = Path.cwd().joinpath("map.html")
m.save(str(f))
webbrowser.open("file://" + str(f))

Plotly Chart-Studio config question to change Modebar in Python

I've created a simple Plotly chart in Python, and I can change the Modebar options quite easily. However, when I'm trying to publish the same chart to Chart-Studio, not all the Modebar configurations are working. Any ideas?
Here is the code:
import pandas as pd
import numpy as np
import plotly.graph_objects as go
df = pd.DataFrame({'a':[2,4,6,8,10],'b':[3,6,9,12,15]})
fig = go.Figure()
fig.add_trace(go.Scatter(x=df.index, y=df['a'], mode='lines', name='a', line=dict(color='dodgerblue', dash='solid')))
fig.add_trace(go.Scatter(x=df.index, y=df['b'], mode='lines', name='b', line=dict(color='lightsalmon', dash='dash')))
fig.update_layout(
title='a and b',
autosize=False,
width=500,
height=500,
newshape=dict(line_color='mediumaquamarine', line_width=2, opacity=1)
)
config = {
'modeBarButtonsToAdd' : ['drawline', 'drawopenpath', 'drawrect', 'eraseshape'],
'displaylogo' : False
}
fig.show(config=config)
The figure that appears has the logo removed and the additional buttons on the modebar showing as it should...
However, if I try to publish this to Chart-Studio:
import chart_studio.plotly as py
import chart_studio
chart_studio.tools.set_credentials_file(username='xxxxx', api_key='#####')
py.plot(fig, filename='a and b', auto_open=False, config=config)
This doesn't work. Note, the logo doesn't appear so I thought that part was working, but actually if I turn displaylogo=True then it doesn't show the logo either. So it appears none of the config arguments are working.
I'm not sure if this is exactly the way to update config in Chart-Studio but I can't find any documentation for it, I tried this based on this old post:
Adding config modes to Plotly.Py offline - modebar
I also tried saving the fig file with the config argument and publishing that but that gives an error. What I've tried here doesn't give an error but it doesn't do anything.
Thanks

Python code doesn't run, I don't know what to do to fix it

class AQGraph:
import pandas as pd
import numpy as np
import matplotlib as plt
PrimaryA = pd.read_csv('PrimaryA.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryA sensor
PrimaryB = pd.read_csv('PrimaryB.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryB sensor
AverageData = np.mean(PrimaryA[:][2], PrimaryB[:][2])
print(AverageData)
plt.plot(PrimaryA[:][0], AverageData)
plt.show()
Attached is my python code. I'm running it in Pycharm and for some reason the green arrow that pops up for Pycharm files isn't there. I've looked through my settings and I'm running Python 3.7. Any advice?
The code you provided, doesn't comply with python rules and standards.
there is a class in your code without any constructor or any method.
Also, you didn't follow Python's indentation policy. Based on what you provided, as soon as you try to run it you should see an error.
import pandas as pd
import numpy as np
import matplotlib as plt
class AQGraph:
#staticmethod
def a_method():
PrimaryA = pd.read_csv('PrimaryA.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryA sensor
PrimaryB = pd.read_csv('PrimaryB.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryB sensor
AverageData = np.mean(PrimaryA[:][2], PrimaryB[:][2])
print(AverageData)
plt.plot(PrimaryA[:][0], AverageData)
plt.show()
if __name__ == "__main__":
AQGraph.a_method()
In the command line try:
> python python_file.py

How to get Bokeh's 'PointDrawTool' working with a NetworkX Spring_Layout

I am working on a network node graph using NetworkX and Bokeh. I am using NetworkX's spring_layout to automatically generate positions for each of my nodes. However, I cannot figure out how to drag the nodes around on my graph (and also have the edges follow along with any dragged nodes).
How do I enable node-dragging for my NetworkX/Bokeh graph?
I have tried using Bokeh's 'PointDrawTool' tool, however, even though the tool renders and shows up in the toolbar next to my graph, it isn't functional.
plot = Plot(plot_width=1000, plot_height=1000,
x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
plot.title.text = "Network Graph"
graph_renderer = from_networkx(G, nx.spring_layout)
plot.add_tools(HoverTool(tooltips=[("ID", "#index"), ("Internal IP", "#Internal")]), PointDrawTool(renderers = [graph_renderer.node_renderer], empty_value = 'black'), TapTool(), BoxSelectTool(), BoxEditTool(), BoxZoomTool(), PanTool(), WheelZoomTool(), ZoomInTool(), ZoomOutTool(), SaveTool(), UndoTool())
graph_renderer.node_renderer.glyph = Circle(size=10, fill_color=Spectral4[0])
graph_renderer.node_renderer.selection_glyph = Circle(size=10, fill_color=Spectral4[2])
graph_renderer.node_renderer.hover_glyph = Circle(size=10, fill_color=Spectral4[1])
graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=1)
graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=3)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=3)
graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = NodesAndLinkedEdges()
plot.renderers.append(graph_renderer)
output_file("interactive_graphs.html")
show(plot)
I expect the nodes to be draggable. I want to click on a node and drag it so that it changes its position.
14/05/2019 Edit:
My imports:
import pandas as pd
import numpy as np
import networkx as nx
from bokeh.io import show, output_file
from bokeh.models import Plot, Range1d, MultiLine, Circle, HoverTool, TapTool, BoxEditTool, BoxSelectTool, BoxZoomTool, ResetTool, PanTool, WheelZoomTool, ZoomInTool, ZoomOutTool, SaveTool, UndoTool, PointDrawTool
from bokeh.models.graphs import from_networkx, NodesAndLinkedEdges, EdgesAndLinkedNodes
from bokeh.palettes import Spectral4
import warnings
import matplotlib.pyplot as plt
%matplotlib notebook
from IPython.display import display, HTML
from IPython.core.interactiveshell import InteractiveShell
From: https://discourse.bokeh.org/t/networkx-import-and-pointdrawtool/3512
"The proximate cause of the problem is that the tool requires access to
glyph.x.field and glyph.y.field but both of these are null for the Circle node
renderer. The GraphRenderer is the only example of a “composite” renderer, so it’s
entirely possible (probable) that there is some interaction problem specific to it
with the PointDrawTool. The next appropriate step would be to make a bug report
issue on GitHub 5 with details."
It would be nice if they solved it.

Categories