Get code:
https://github.com/MoreYoungGavin/Learning-Jupyter.git
Install Jupyter
Pip install jupyter
Work Jupyter
Start Jupyter
You can click New,choose Python3,start your jupyter travel
Helloworld
Draw line graph
Result display is as below:
How to do it?
import pandas
import matplotlib
%matplotlib inline
baby_name = ['Alice','Charles','Diane','Edward']
number_births = [96, 155, 66, 272]
dataset = list(zip(baby_name,number_births))
df = pandas.DataFrame(data = dataset, columns=['Name', 'Number'])
df['Number'].plot()
Drwa histogram
Result display is as below:
How to do it?
import pylab
import random
random.seed(113)
samples = 1000
dice = []
for i in range(samples):
total = random.randint(1,6) + random.randint(1,6)
dice.append(total)
pylab.hist(dice, bins= pylab.arange(1.5,12.6,1.0))
pylab.show()
Drwa density map
Result display is as below:
How to do it?
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
import pandas as pd
import numpy as np
import matplotlib
# create the map
map = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,projection='lcc',lat_1=33,lat_2=45,lon_0=-95) # load the shapefile, use the name 'states'
# download from https://github.com/matplotlib/basemap/tree/master/examples/st99_d00.dbf,shx,shp
map.readshapefile('st99_d00', name='states', drawbounds=True)
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
# load density data drawn from
# https://en.wikipedia.org/wiki/List_of_U.S._states_by_population_density
df = pd.read_csv('states.csv')
# determine the range of density values
max_density = -1.0
min_density = -1.0
for index, row in df.iterrows():
d = row['density/mi2']
density = float(d.replace(',' , ''))
if (max_density==-1.0) or (max_density<density):
max_density = density
if (min_density==-1.0) or (min_density>density):
min_density = density
print('max',max_density)
print('min',min_density)
range_density = max_density - min_density
print(range_density)
# we pick a color for the state density out of red spectrum
cmap = matplotlib.cm.get_cmap('Spectral')
# for each state get the color for it's density
for index, row in df.iterrows():
state_name = row['State']
d = row['density/mi2']
density = float(d.replace(',' , ''))
color = cmap((density - min_density)/range_density)
seg = map.states[state_names.index(state_name)]
poly = Polygon(seg, facecolor=color, edgecolor=color)
ax.add_patch(poly)
plt.show()
Plot 3D data
Result display is as below:
How to do it?
# import tools we are using
import pandas as pd
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
# read in the car ‘table’ – not a csv, so we need
# to add in the column names
column_names = ['mpg', 'cylinders', 'displacement', 'horsepower','weight', 'acceleration', 'year', 'origin', 'name']
df = pd.read_table('http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data', sep=r"\s+", index_col=0, header=None,names = column_names)
print(df.head())
#start out plotting (uses a subplot as that can be 3d)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')# pull out the 3 columns that we want
xs = []
ys = []
zs = []
for index, row in df.iterrows():
xs.append(row['weight'])
ys.append(index) #read_table uses first column as index
zs.append(row['cylinders'])# based on our dataset the extents of the axes
plt.xlim(min(xs), max(xs))
plt.ylim(min(ys), max(ys))
ax.set_zlim(min(zs), max(zs))
# standard scatter diagram (except it is 3d)
ax.scatter(xs, ys, zs)
ax.set_xlabel('Weight')
ax.set_ylabel('MPG')
ax.set_zlabel('Cylinders')
plt.show()
Present user-interactive graphic
Result display is as below:
How to do it?
from bokeh.io import output_notebook, show
from bokeh.layouts import widgetbox
from bokeh.models.widgets import TextInput
from bokeh.models import WidgetBox, Button
import numpy as np
import pandas as pd
from bokeh.plotting import figure, show
from bokeh.layouts import layout
# output_notebook()
# load the vote counts
from_counts = np.load("from_counts.npy")
# convert array to a dataframe (Histogram requires a dataframe)
df = pd.DataFrame({'Votes':from_counts})
#print(df.head())
p = figure(plot_height=200,plot_width=600, title="How Many Votes Made byUsers")
p.vbar(x=range(0,6110), width=0.5, bottom=0,top=df.Votes, color="firebrick")
button = Button(label="Foo", button_type="success")
text = TextInput(title="title", value='A Text Box')
widgets = WidgetBox(button, text)
l = layout([p,widgets])
show(l)
Button Widget
How to do it?
import ipywidgets as widgets
from IPython.display import display
my_button = widgets.Button(description='Click My Button')
display(my_button)
def my_button_clicked(b):
print("You clicked on My Button")
my_button.on_click(my_button_clicked)
It give this display:
Ipyleaflet Widget
How to do it?
from ipyleaflet import *
m = Map(zoom=4, basemap=basemaps.Esri.WorldStreetMap)
m
m.zoom
It give this display:
Ipywidget Widget
How to do it?
import ipywidgets as widgets
widgets.RadioButtons(options=['red', 'green', 'blue'],description='Balloon color:',disabled=False)
It give this display:
Widget Container
How to do it?
from ipywidgets import *
from IPython.display import display
slider = widgets.FloatSlider()
message = widgets.Text(value='Hello World')
container = widgets.Box(children=[slider, message])
container.layout.border = '1px black solid'
display(container)
It give this display:
Interactive Widget
How to do it?
def mycheckfunction(x):
print(x)
return x
interactive_checkbox = interactive(mycheckfunction, x=False)
interactive_checkbox
It give this display:
Interactive Text Widget
How to do it?
def mytextfunction(x):
print(x)
return x
interactive_text = interactive(mytextfunction, x="Hello World")
interactive_text
It give this display:
Link Widget Together
How to do it?
import ipywidgets as widgets
floatTextBox = widgets.FloatText()
floatSlider = widgets.FloatSlider()
display(floatTextBox,floatSlider)
widgetLink = widgets.jslink((floatTextBox, 'value'), (floatSlider,'value'))
It give this display:
Another Ipywidgets Link Example
How to do it?
%matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np
def f(r):
plt.axes()
circle = plt.Circle((0, 0), radius=r, fc='y')
plt.gca().add_patch(circle)
plt.axis('scaled')
plt.show()
interactive_plot = interactive(f, r=(0.0, 1.0))
output = interactive_plot.children[-1]
output.layout.height = '350px'
interactive_plot
It give this display:
Jupyter Dashboard
Get Ready
pip install jupyter_dashboards
jupyter dashboards quick-setup --sys-prefix
Create Python Dashboard
How to do it?
import pandas as pd
import numpy as np
import statsmodels.formula.api as sm
import matplotlib.pylab as plt
%matplotlib inline
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 15, 6
data = pd.read_csv("grapeJuice.csv")
data.head()
data["sales"] = data["sales"] / 20
plt.plot(data); #suppresses extraneous matplotlib messages
It give this display:
Next:
Y = data['sales'][:-1]
X = data[['price','ad_type','price_apple','price_cookies']][:-1]
result = sm.OLS( Y, X ).fit()
result.summary()
It give this display:
JupyterLab
Get Ready
Pip install jupyterlab
Start Jupyterlab
Console