%matplotlib inline import matplotlib.pyplot as plt # side-stepping mpl backend import matplotlib.gridspec as gridspec # subplots import numpy as np import plotly.plotly as py import plotly.tools as tls from plotly.graph_objs import * py.sign_in("IPython.Demo", "1fw3zw2o13") # tls.set_credentials_file("IPython.Demo", "1fw3zw2o13") # tls.get_credentials_file() import plotly plotly.__version__ fig1 = plt.figure() # Make a legend for specific lines. import matplotlib.pyplot as plt import numpy as np t1 = np.arange(0.0, 2.0, 0.1) t2 = np.arange(0.0, 2.0, 0.01) # note that plot returns a list of lines. The "l1, = plot" usage # extracts the first element of the list into l1 using tuple # unpacking. So l1 is a Line2D instance, not a sequence of lines l1, = plt.plot(t2, np.exp(-t2)) l2, l3 = plt.plot(t2, np.sin(2 * np.pi * t2), '--go', t1, np.log(1 + t1), '.') l4, = plt.plot(t2, np.exp(-t2) * np.sin(2 * np.pi * t2), 'rs-.') plt.xlabel('time') plt.ylabel('volts') plt.title('Damped oscillation') plt.show() py.iplot_mpl(fig1) fig = tls.mpl_to_plotly(fig1) fig['layout'].update(showlegend=True) fig.strip_style() py.iplot(fig) fig2 = plt.figure() from pylab import * def f(t): 'a damped exponential' s1 = cos(2*pi*t) e1 = exp(-t) return multiply(s1,e1) t1 = arange(0.0, 5.0, .2) l = plot(t1, f(t1), 'ro') setp(l, 'markersize', 30) setp(l, 'markerfacecolor', 'b') py.iplot_mpl(fig2) tls.mpl_to_plotly(fig2).get_data() pylab = py.get_figure('IPython.Demo', '3357') #print figure print pylab.to_string() from IPython.display import Image Image(url='https://i.imgur.com/WG0gb9J.png') Image(url='https://i.imgur.com/Mq490fb.png') tls.embed('MattSundquist', '1307') from IPython.display import HTML s = """
<iframe src="https://plot.ly/~etpinard/176/650/550" width="650" height=550" frameBorder="0" seamless="seamless" scrolling="no"></iframe>
""" h = HTML(s); h Image(url='http://i.imgur.com/XjvtYMr.png') HTML('

') Image(url='https://i.imgur.com/CxIYtzG.png') Image(url='https://i.imgur.com/gUC4ajR.png') fig3 = plt.figure() import numpy as np import matplotlib.pyplot as plt # make a little extra space between the subplots plt.subplots_adjust(wspace=0.5) dt = 0.01 t = np.arange(0, 30, dt) nse1 = np.random.randn(len(t)) # white noise 1 nse2 = np.random.randn(len(t)) # white noise 2 r = np.exp(-t/0.05) cnse1 = np.convolve(nse1, r, mode='same')*dt # colored noise 1 cnse2 = np.convolve(nse2, r, mode='same')*dt # colored noise 2 # two signals with a coherent part and a random part s1 = 0.01*np.sin(2*np.pi*10*t) + cnse1 s2 = 0.01*np.sin(2*np.pi*10*t) + cnse2 plt.subplot(211) plt.plot(t, s1, 'b-', t, s2, 'g-') plt.xlim(0,5) plt.xlabel('time') plt.ylabel('s1 and s2') plt.grid(True) plt.subplot(212) cxy, f = plt.csd(s1, s2, 256, 1./dt) plt.ylabel('CSD (db)') py.iplot_mpl(fig3) fig4 = plt.figure() from pylab import figure, show from numpy import arange, sin, pi t = arange(0.0, 1.0, 0.01) fig = figure(1) ax1 = fig.add_subplot(211) ax1.plot(t, sin(2*pi*t)) ax1.grid(True) ax1.set_ylim( (-2,2) ) ax1.set_ylabel('1 Hz') ax1.set_title('A sine wave or two') for label in ax1.get_xticklabels(): label.set_color('r') ax2 = fig.add_subplot(212) ax2.plot(t, sin(2*2*pi*t)) ax2.grid(True) ax2.set_ylim( (-2,2) ) l = ax2.set_xlabel('Hi mom') l.set_color('g') l.set_fontsize('large') py.iplot_mpl(fig4, strip_style = True) fig5 = plt.figure() 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 """ from pylab import * x = array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]) y1 = array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]) y2 = array([9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74]) y3 = array([7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73]) x4 = array([8,8,8,8,8,8,8,19,8,8,8]) y4 = 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 xfit = array( [amin(x), amax(x) ] ) subplot(221) plot(x,y1,'ks', xfit, fit(xfit), 'r-', lw=2) axis([2,20,2,14]) setp(gca(), xticklabels=[], yticks=(4,8,12), xticks=(0,10,20)) text(3,12, 'I', fontsize=20) subplot(222) plot(x,y2,'ks', xfit, fit(xfit), 'r-', lw=2) axis([2,20,2,14]) setp(gca(), xticklabels=[], yticks=(4,8,12), yticklabels=[], xticks=(0,10,20)) text(3,12, 'II', fontsize=20) subplot(223) plot(x,y3,'ks', xfit, fit(xfit), 'r-', lw=2) axis([2,20,2,14]) text(3,12, 'III', fontsize=20) setp(gca(), yticks=(4,8,12), xticks=(0,10,20)) subplot(224) xfit = array([amin(x4),amax(x4)]) plot(x4,y4,'ks', xfit, fit(xfit), 'r-', lw=2) axis([2,20,2,14]) setp(gca(), yticklabels=[], yticks=(4,8,12), xticks=(0,10,20)) 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'%(mean(y), std(y), corrcoef(x,y)[0][1])) py.iplot_mpl(fig5, strip_style = True) fig6 = plt.figure() import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt # example data mu = 100 # mean of distribution sigma = 15 # standard deviation of distribution x = mu + sigma * np.random.randn(10000) num_bins = 50 # the histogram of the data n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5) # add a 'best fit' line y = mlab.normpdf(bins, mu, sigma) plt.plot(bins, y, 'r--') plt.xlabel('Smarts') plt.ylabel('Probability') # Tweak spacing to prevent clipping of ylabel plt.subplots_adjust(left=0.15) py.iplot_mpl(fig6, strip_style = True) Image(url='https://i.imgur.com/HEJEnjQ.png') from ggplot import * a = ggplot(aes(x='price'), data=diamonds) + geom_histogram() + facet_wrap("cut") fig = a.draw() py.iplot_mpl(fig, strip_style=True) b = ggplot(aes(x='date', y='beef'), data=meat) + \ geom_line() fig = b.draw() py.iplot_mpl(fig) c = ggplot(aes(x='price'), data=diamonds) + geom_histogram() + ggtitle('My Diamond Histogram') fig = c.draw() py.iplot_mpl(fig, strip_style=True) d = ggplot(aes(x='x', y='y', color='z'), data=diamonds.head(1000)) +\ geom_point() fig = d.draw() py.iplot_mpl(fig, strip_style=True) import pandas as pd random_walk1 = pd.DataFrame({ "x": np.arange(100), "y": np.cumsum(np.random.choice([-1, 1], 100)) }) random_walk2 = pd.DataFrame({ "x": np.arange(100), "y": np.cumsum(np.random.choice([-1, 1], 100)) }) e = ggplot(aes(x='x', y='y'), data=random_walk1) + \ geom_step() + \ geom_step(aes(x='x', y='y'), data=random_walk2) fig = e.draw() py.iplot_mpl(fig, strip_style=True) fig12 = plt.figure() import prettyplotlib as ppl # Set the random seed for consistency np.random.seed(12) # Show the whole color range for i in range(8): x = np.random.normal(loc=i, size=800) y = np.random.normal(loc=i, size=800) ax = ppl.scatter(x, y, label=str(i)) ppl.legend(ax) ax.set_title('prettyplotlib `scatter`') ax.legend().set_visible(False) py.iplot_mpl(fig12) fig13 = plt.figure() import prettyplotlib as ppl # Set the random seed for consistency np.random.seed(12) # Show the whole color range for i in range(8): y = np.random.normal(size=1000).cumsum() x = np.arange(1000) # Specify both x and y ppl.plot(x, y, label=str(i), linewidth=0.75) py.iplot_mpl(fig13) import seaborn as sns from matplotlylib import fig_to_plotly def sinplot(flip=1): x = np.linspace(0, 14, 100) for i in range(1, 7): plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip) fig14 = plt.figure() sns.set_style("dark") sinplot() py.iplot_mpl(fig14, strip_style = True) fig15 = plt.figure() with sns.axes_style("darkgrid"): plt.subplot(211) sinplot() plt.subplot(212) sinplot(-1) py.iplot_mpl(fig15, strip_style = True) import numpy as np from numpy.random import randn import pandas as pd from scipy import stats import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns fig16 = plt.figure() sns.set_palette("hls") mpl.rc("figure", figsize=(8, 4)) data = randn(200) sns.distplot(data); py.iplot_mpl(fig16, strip_style = True) fig17 = plt.figure() import matplotlib.pyplot as plt import numpy as np mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) hist, bins = np.histogram(x, bins=50) width = 0.7 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 plt.bar(center, hist, align='center', width=width) py.iplot_mpl(fig17, strip_style = True) fig18 = plt.figure() import matplotlib.pyplot as plt import numpy as np from scipy.stats import gaussian_kde data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8 density = gaussian_kde(data) xs = np.linspace(0,8,200) density.covariance_factor = lambda : .25 density._compute_covariance() plt.plot(xs,density(xs)) py.iplot_mpl(fig18, strip_style = True) fig19 = plt.figure() import matplotlib.pyplot as plt import numpy as np x = np.arange(10) plt.plot(x, x) plt.plot(x, 2 * x) plt.plot(x, 3 * x) plt.plot(x, 4 * x) py.iplot_mpl(fig19, strip_style = True) fig20 = plt.figure() import matplotlib.pyplot as plt import numpy as np num_plots = 10 # Have a look at the colormaps here and decide which one you'd like: # http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html colormap = plt.cm.gist_ncar plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, num_plots)]) # Plot several different functions... x = np.arange(10) labels = [] for i in range(1, num_plots + 1): plt.plot(x, i * x + 5 * i) labels.append(r'$y = %ix + %i$' % (i, 5*i)) py.iplot_mpl(fig20, strip_style = True) fig21 = plt.figure() import matplotlib.pyplot as plt import numpy as np import matplotlib.mlab as mlab mean = [10,12,16,22,25] variance = [3,6,8,10,12] x = np.linspace(0,40,1000) for i in range(4): sigma = np.sqrt(variance[i]) y = mlab.normpdf(x,mean[i],sigma) plt.plot(x,y, label=r'$v_{}$'.format(i+1)) plt.xlabel("X") plt.ylabel("P(X)") py.iplot_mpl(fig21, strip_style = True) # CSS styling within IPython notebook from IPython.core.display import HTML import urllib2 def css_styling(): url = 'https://raw.githubusercontent.com/plotly/python-user-guide/master/custom.css' styles = urllib2.urlopen(url).read() return HTML(styles) css_styling()