In [2]:
# This command instructs the jupyter notebook to place the figures inline
%matplotlib inline
# Allows interaction in a separate window
#%matplotlib
#%matplotlib
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pylab as plt
df_enerji = pd.read_csv(u'data/enerji.csv',sep=';')
df_enerji
Out[2]:
In [3]:
print(df_enerji.columns)
x = df_enerji.Year
y = df_enerji.Total/1000
fig = plt.figure(figsize=(10,4))
plt.plot(x, y)
plt.title('Total Energy consumption in Turkey (in Tera-Watt-hours TWh)')
plt.xlabel('Year')
plt.ylabel('Energy Consumption/TWh')
plt.show()
#mpld3.display(fig)
In [4]:
sector = 'Commercial'
plt.plot(x, y*df_enerji[sector], 'o-')
plt.title('Energy use in Turkey by the '+sector+' sector')
plt.show()
plt.plot(x, df_enerji[sector], 'o-')
plt.title('Percentage of Energy use in Turkey by the '+sector+' sector')
plt.show()
In [5]:
sector1 = 'Commercial'
sector2 = 'Household'
x1 = df_enerji['Total']*df_enerji[sector1]/1000
x2 = df_enerji['Total']*df_enerji[sector2]/1000
plt.plot(x1, x2, 'o')
plt.xlabel(sector1)
plt.ylabel(sector2)
plt.title('Energy use in Turkey by '+sector1+' versus '+sector2)
plt.show()
In [6]:
from __future__ import print_function
"""
Edward Tufte uses this example from Anscombe to show 4 datasets of x
and y that have the same mean, standard deviation, and regression
line, but which are qualitatively different.
matplotlib fun for a rainy day
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5])
y1 = np.array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68])
y2 = np.array([9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74])
y3 = np.array([7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73])
x4 = np.array([8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8])
y4 = np.array([6.58, 5.76, 7.71, 8.84, 8.47, 7.04, 5.25, 12.50, 5.56, 7.91, 6.89])
def fit(x):
return 3 + 0.5*x
plt.figure(figsize=(8,8))
xfit = np.array([np.amin(x), np.amax(x)])
plt.subplot(221)
plt.plot(x, y1, 'ks', xfit, fit(xfit), 'r-', lw=2)
plt.axis([2, 20, 2, 14])
plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20))
plt.text(3, 12, 'I', fontsize=20)
plt.subplot(222)
plt.plot(x, y2, 'ks', xfit, fit(xfit), 'r-', lw=2)
plt.axis([2, 20, 2, 14])
plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), yticklabels=[], xticks=(0, 10, 20))
plt.text(3, 12, 'II', fontsize=20)
plt.subplot(223)
plt.plot(x, y3, 'ks', xfit, fit(xfit), 'r-', lw=2)
plt.axis([2, 20, 2, 14])
plt.text(3, 12, 'III', fontsize=20)
plt.setp(plt.gca(), yticks=(4, 8, 12), xticks=(0, 10, 20))
plt.subplot(224)
xfit = np.array([np.amin(x4), np.amax(x4)])
plt.plot(x4, y4, 'ks', xfit, fit(xfit), 'r-', lw=2)
plt.axis([2, 20, 2, 14])
plt.setp(plt.gca(), yticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20))
plt.text(3, 12, 'IV', fontsize=20)
# verify the stats
pairs = (x, y1), (x, y2), (x, y3), (x4, y4)
for x, y in pairs:
print('mean=%1.2f, std=%1.2f, r=%1.2f' % (np.mean(y), np.std(y), np.corrcoef(x, y)[0][1]))
plt.show()
In [2]:
'''
=================================
3D surface with polar coordinates
=================================
Demonstrates plotting a surface defined in polar coordinates.
Uses the reversed version of the YlGnBu color map.
Also demonstrates writing axis labels with latex math mode.
Example contributed by Armin Moser.
'''
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Create the mesh in polar coordinates and compute corresponding Z.
r = np.linspace(0, 1.25, 50)
p = np.linspace(0, 2*np.pi, 50)
R, P = np.meshgrid(r, p)
Z = ((R**2 - 1)**2)
# Express the mesh in the cartesian system.
X, Y = R*np.cos(P), R*np.sin(P)
# Plot the surface.
ax.plot_surface(X, Y, Z, cmap=plt.cm.YlGnBu_r)
# Tweak the limits and add latex math labels.
ax.set_zlim(0, 1)
ax.set_xlabel(r'$\phi_\mathrm{real}$')
ax.set_ylabel(r'$\phi_\mathrm{im}$')
ax.set_zlabel(r'$V(\phi)$')
plt.show()
In [3]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
## See http://matplotlib.org/examples/showcase/xkcd.html
#if 1:
with plt.xkcd():
# Based on "Stove Ownership" from XKCD by Randall Monroe
# http://xkcd.com/418/
fig = plt.figure()
data = np.random.rand(10)
plt.hist(data)
plt.show()
In [1]:
%matplotlib inline
import numpy as np
import pandas as pd
from scipy import stats, integrate
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)
x = np.random.normal(size=64)
plt.figure(figsize=(16,6))
plt.subplot(2,2,1)
sns.distplot(x, kde=False, hist=True, bins=50, fit=stats.invgauss, rug=True);
plt.subplot(2,2,2)
sns.distplot(x, kde=False, rug=True, bins=30);
In [2]:
mean, cov = [0, 1], [(1, .5), (.5, 1)]
data = np.random.multivariate_normal(mean, cov, 200)
df = pd.DataFrame(data, columns=["x", "y"])
sns.jointplot(x="x", y="y", data=df);
plt.show()
In [7]:
x, y = np.random.multivariate_normal(mean, cov, 1000).T
with sns.axes_style("white"):
sns.jointplot(x=x, y=y, kind="hex", color="k");
In [4]:
sns.jointplot(x="x", y="y", data=df, kind="kde");
In [5]:
f, ax = plt.subplots(figsize=(6, 6))
sns.kdeplot(df.x, df.y, ax=ax)
sns.rugplot(df.x, color="g", ax=ax)
sns.rugplot(df.y, vertical=True, ax=ax);
In [6]:
f, ax = plt.subplots(figsize=(6, 6))
cmap = sns.cubehelix_palette(as_cmap=True, dark=0, light=1, reverse=True)
sns.kdeplot(df.x, df.y, cmap=cmap, n_levels=60, shade=True);
In [7]:
g = sns.jointplot(x="x", y="y", data=df, kind="kde", color="m")
g.plot_joint(plt.scatter, c="w", s=30, linewidth=1, marker="+")
g.ax_joint.collections[0].set_alpha(0)
g.set_axis_labels("$X$", "$Y$");
In [8]:
iris = sns.load_dataset("iris")
sns.pairplot(iris);
In [9]:
g = sns.PairGrid(iris)
g.map_diag(sns.kdeplot)
g.map_offdiag(sns.kdeplot, cmap="Blues_d", n_levels=6);
In [12]:
plt.get_backend()
Out[12]:
In [8]:
import numpy as np
import matplotlib.pyplot as plt
# Example data
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.plot(t, s)
plt.xlabel(r'\textbf{time} (s)')
plt.ylabel(r'\textit{voltage} (mV)',fontsize=16)
plt.title(r"\TeX\ is Number "
r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
fontsize=16, color='gray')
# Make room for the ridiculously large title.
plt.subplots_adjust(top=0.8)
#plt.savefig('tex_demo')
plt.show()
In [16]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, rc
from IPython.display import HTML
# equivalent to rcParams['animation.html'] = 'html5'
rc('animation', html='html5')
# First set up the figure, the axis, and the plot element we want to animate
fig, ax = plt.subplots()
ax.set_xlim(( 0, 2))
ax.set_ylim((-2, 2))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return (line,)
# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return (line,)
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=10, blit=True)
In [17]:
anim
Out[17]:
In [18]:
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
plt.rcParams["animation.html"] = "jshtml"
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])
def animate(i):
l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
from IPython.display import HTML
HTML(ani.to_jshtml())
In [3]:
%matplotlib inline
#%matplotlib tkagg
# update a distribution based on new data.
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as ss
from matplotlib.animation import FuncAnimation
plt.rcParams["animation.html"] = "jshtml"
class UpdateDist(object):
def __init__(self, ax, prob=0.5):
self.success = 0
self.prob = prob
self.line, = ax.plot([], [], 'k-')
self.x = np.linspace(0, 1, 200)
self.ax = ax
# Set up plot parameters
self.ax.set_xlim(0, 1)
self.ax.set_ylim(0, 15)
self.ax.grid(True)
# This vertical line represents the theoretical value, to
# which the plotted distribution should converge.
self.ax.axvline(prob, linestyle='--', color='black')
def init(self):
self.success = 0
self.line.set_data([], [])
return self.line,
def __call__(self, i):
# This way the plot can continuously run and we just keep
# watching new realizations of the process
if i == 0:
return self.init()
# Choose success based on exceed a threshold with a uniform pick
if np.random.rand(1,) < self.prob:
self.success += 1
y = ss.beta.pdf(self.x, self.success + 1, (i - self.success) + 1)
self.line.set_data(self.x, y)
return self.line,
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ud = UpdateDist(ax, prob=0.7)
anim = FuncAnimation(fig, ud, frames=200, init_func=ud.init,
interval=100, blit=False)
from IPython.display import HTML
HTML(anim.to_jshtml())
In [19]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
class ParticleAnimator(object):
def __init__(self, N=1, plot_coords=False, gravity=0.008):
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], frameon=True)
ax.set_xlim(0, 1), ax.set_xticks([])
ax.set_ylim(0, 1), ax.set_yticks([])
self.fig = fig
self.ax = ax
self.N = N
self.x = np.zeros((2,N))
self.y = np.zeros((2,N))
self.A = np.matrix('[1,0.25;0,1]')
self.g = gravity
self.plot_coords = plot_coords
def reset_variables(self):
self.x[0,:] = np.random.rand(1,self.N)
self.x[1,:] = np.random.randn(1,self.N)/5
self.y[0,:] = 0.9
self.y[1,:] = 0
# Particles
#self.ln, = plt.plot(self.x[0,:], self.y[0,:], 'go')
self.ln, = plt.plot([], [], 'go')
# Lines from origin, x and y axes
#self.ln2, = plt.plot([self.x[0,0], 0], [self.y[0,0], 0], '--')
self.ln2, = plt.plot([], [], '--')
self.lnx, = plt.plot([], [],'b--')
self.lny, = plt.plot([], [], 'r--')
return self.ln
def __call__(self, frame_number):
if frame_number==0:
return self.reset_variables()
self.x = self.A*self.x + np.matrix('[0;-1]')*np.random.randn(1)*0.0005
self.y = self.A*self.y + np.matrix('[0;-1]')*self.g
for i in range(self.N):
if self.x[0,i]<0:
self.x[0,i]=0
self.x[1,i]=-1.0*self.x[1,i]
if self.x[0,i]>1:
self.x[0,i] = 1
self.x[1,i]=-1.0*self.x[1,i]
if self.y[0,i]<0:
self.y[0,i]=0
self.y[1,i]=-1.05*self.y[1,i]
if self.y[0,i]>1:
self.y[0,i] = 1
self.y[1,i]=-0.2*self.y[1,i]
self.ln.set_xdata(self.x[0,:].tolist()[0])
self.ln.set_ydata(self.y[0,:].tolist()[0])
if self.plot_coords:
x0 = self.x[0,0]
y0 = self.y[0,0]
self.ln2.set_xdata([x0, 0])
self.lnx.set_xdata([x0, x0])
self.lny.set_xdata([0, x0 ])
# ln.set_ydata(y[0,:])
self.ln2.set_ydata([y0, 0])
self.lnx.set_ydata([0, y0])
self.lny.set_ydata([y0, y0])
self.fig.gca().set_title(frame_number)
return self.ln
# Number of particles to simulate
pa = ParticleAnimator(N=1, plot_coords=False, gravity=0.005)
anim_obj = FuncAnimation(pa.fig, pa, frames=200, interval=10)
from IPython.display import HTML
HTML(anim_obj.to_jshtml())
In [6]:
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
from IPython.display import clear_output, display, HTML
from matplotlib import rc
import scipy as sc
import scipy.optimize as opt
def sigmoid(x):
return 1/(1+np.exp(-x))
def inv_sigmoid(p=0.5):
xs = opt.bisect(lambda x: sigmoid(x)-p, a=-100, b=100)
return xs
def inv_sigmoid1D(w, b, p=0.5):
xs = opt.bisect(lambda x: sigmoid(w*x+b)-p, a=-100, b=100)
return xs
fig = plt.figure(figsize=(10,6))
ax = fig.gca()
ax.set_ylim([-0.1,1.1])
x = np.linspace(-10,10,100)
ax.set_xlim([-10,10])
ln = plt.Line2D(x, sigmoid(x))
ln2 = plt.axvline([0], ls= ':', color='k')
ln_left = plt.axvline([0], ls= ':', color='b')
ln_right = plt.axvline([0], ls= ':', color='r')
ax.add_line(ln)
plt.close(fig)
ax.set_xlabel('$x$')
ax.set_ylabel('$\sigma(wx + b)$')
def plot_fun(w, b):
ln.set_ydata(sigmoid(w*x+b))
if np.abs(w)>0.00001:
ln2.set_xdata(inv_sigmoid1D(w,b,0.5))
ln_left.set_xdata(inv_sigmoid1D(w,b,0.25))
ln_right.set_xdata(inv_sigmoid1D(w,b,0.75))
display(fig)
res = interact(plot_fun, w=(-3, 3, 0.1), b=(-10.0,10.0,0.1))
In [6]:
%pylab inline
In [13]:
from tempfile import NamedTemporaryFile
VIDEO_TAG = """<video controls>
<source src="data:video/x-m4v;base64,{0}" type="video/mp4">
Your browser does not support the video tag.
</video>"""
def anim_to_html(anim):
if not hasattr(anim, '_encoded_video'):
with NamedTemporaryFile(suffix='.mp4') as f:
anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264', '-pix_fmt', 'yuv420p'])
video = open(f.name, "rb").read()
anim._encoded_video = video.encode("base64")
return VIDEO_TAG.format(anim._encoded_video)
In [11]:
from IPython.display import HTML
def display_animation(anim):
plt.close(anim._fig)
return HTML(anim_to_html(anim))
In [14]:
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=40, blit=True)
# call our new function to display the animation
display_animation(anim)
In [15]:
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(-2, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2,marker='o')
N = 10
global x
global y
x = np.random.rand(N)*2 - 1
y = np.random.rand(N)*2 - 1
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
global x,y
x = x + 0.01*np.random.randn(N)
y = y + 0.01*np.random.randn(N)
line.set_data(x, y)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim2 = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=40, blit=True)
# call our new function to display the animation
display_animation(anim2)
In [9]:
"""
===========================
Plots with different scales
===========================
Demonstrate how to do two plots on the same axes with different left and
right scales.
The trick is to use *two different axes* that share the same *x* axis.
You can use separate `matplotlib.ticker` formatters and locators as
desired since the two axes are independent.
Such axes are generated by calling the `Axes.twinx` method. Likewise,
`Axes.twiny` is available to generate axes that share a *y* axis but
have different top and bottom scales.
The twinx and twiny methods are also exposed as pyplot functions.
"""
import numpy as np
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('exp', color='b')
ax1.tick_params('y', colors='b')
ax2 = ax1.twinx()
s2 = np.sin(2 * np.pi * t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin', color='r')
ax2.tick_params('y', colors='r')
fig.tight_layout()
plt.show()
In [10]:
"""
===============
Watermark image
===============
Use a PNG file as a watermark
"""
from __future__ import print_function
import numpy as np
import matplotlib.cbook as cbook
import matplotlib.image as image
import matplotlib.pyplot as plt
datafile ='data/boun_logo.png'
print('loading %s' % datafile)
im = image.imread(datafile)
im[:, :, -1] = 0.03 # set the alpha channel
fig, ax = plt.subplots()
ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')
ax.grid()
fig.figimage(im, 0, 0, zorder=3, resize=True)
plt.show()
In [11]:
"""
===========================================
Changing colors of lines intersecting a box
===========================================
The lines intersecting the rectangle are colored in red, while the others
are left as blue lines. This example showcases the `intersect_bbox` function.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
from matplotlib.path import Path
left, bottom, width, height = (1, -1, 2, 2)
rect = plt.Rectangle((left, bottom), width, height, facecolor="#aaaaaa")
fig, ax = plt.subplots()
ax.add_patch(rect)
bbox = Bbox.from_bounds(left, bottom, width, height)
for i in range(12):
vertices = (np.random.random((2, 2)) - 0.5) * 6.0
path = Path(vertices)
if path.intersects_bbox(bbox):
color = 'r'
else:
color = 'b'
ax.plot(vertices[:, 0], vertices[:, 1], color=color)
plt.show()